Python Dictionaries

Use dict.get(x) and not dict[x]

>>> a = {"name": "sandipb", "age": 16}

>>> print a["height"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'height'

>>> print a.get("height")
None

>>> HEIGHT_UNSET = "0"
>>> print a.get("height", HEIGHT_UNSET)
0
>>> if a.get("height", HEIGHT_UNSET) == HEIGHT_UNSET:
...     print "height not set"
... 
height not set

>>> if not a["height"]:
...     print "height not set"
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'height'

Use dict.setdefault(k,v) when you are building a dict with mutable values, and want to ensure that the entries have a default value before you start modifying it

Here is a program which gives you the frequency of alphabets in a string, and its positions.

   1 import sys
   2 
   3 if len(sys.argv) > 1:
   4     word = " ".join(sys.argv[1:])
   5 else:
   6     word = "A big hello to the entire world"
   7 
   8 # Storing positions of the alpha in the string
   9 alphacount = {}
  10 
  11 for pos,c in enumerate(word):
  12 #    print "[" + str(pos) + "] = ", c
  13     if c in alphacount:
  14         alphacount[c].append(pos)
  15     else:
  16         alphacount[c] = [] #Understand this is not required,
  17                            # Just that some languages require
  18                            # you to do something similar. e.g.
  19                            # malloc() if doing this in C
  20         alphacount[c].append( pos)
  21 
  22 print "word is [" + word + "]"
  23 print "word is [" + "".join( map(str, (x % 10 for x in range(len(word))))) + "]"
  24 
  25 for c in alphacount:
  26     print "%s: %d times, positions %s" % ( c, 
  27                                            len(alphacount[c]), 
  28                                            ",".join(map(str, alphacount[c])))
  29 

$ python newdict.py hello there
word is [hello there]
word is [01234567890]
 : 1 times, positions 5
e: 3 times, positions 1,8,10
h: 2 times, positions 0,7
l: 2 times, positions 2,3
o: 1 times, positions 4
r: 1 times, positions 9
t: 1 times, positions 6

The dict buildup here has to check if a key exists, if not, then has to create an empty list, and only then do a modification of the list by adding the line position into it.

It is this kind of logic which is solved using dict.setdefault(). In this case, that whole conditional (line 11 - 20 above ) can be replaced with:

   1 for pos,c in enumerate(word):
   2     alphacount.setdefault(c, []).append(pos)
   3 

* Reference: Python cookbook entry

Python/Dictionaries (last edited 2010-06-14 13:02:50 by SandipBhattacharya)