A Python question: adding to an empty hash
In Perl, you can do nice efficient things like this:
$hashName{$keyName}++; which says, “add 1 to the value corresponding to the key $keyName, in the hash called $hashName.” In Python, as far as I can tell, you have to be a bit more verbose:
hashName = {} if hashName.has_key(keyName): hashName[keyName] += 1 else: hashName[keyName] = 1 Come to think of it, this points out three little annoyances in Python, the others being
The absence of a
++operator; you have to use+= 1instead. Not a huge deal, but every other language you’d care to use nowadays has a++operator.Data structures have to be initialized before they can be used: you can’t just start adding key/value pairs to a nonexistent hash.
Anyway, does anyone know if there’s a shorter way to do the dictionary addition?
P.S.: While I’m at it, here’s another Python oddity that I will probably get used to eventually, but which puzzles me now: you can write statements like
list = [1,2,3] print max(list) and get back what you would expect — namely “3”. But if you do
list = [1,2,3] print "The largest item in the list is " + max(list) you will get an interpreter error: the “+” operator won’t let you concatenate variables of type string (“The largest item in the list is”) with those of type int (“max(list)”).
The print function knows how to coerce ints into strings; why can’t the “+” operator do the same? The C++ approach would be to overload the “<<” operator for whatever type you’re trying to print, so that you can do (relatively) clear things like so:
cout << "The largest item in the list is " << max(list); and get back what you’d expect.