Monday, October 5, 2009

Python 101: How to iterate a dictionary/hash



For those who don't know, python dictionary == perl hash.

The most common idiom uses the iteritems function:

mydict = { "a" : "Alpha", "b" : "Beta", "c" : "Charlie" }
for key, value in mydict.iteritems():
print key, value

The iteritems function returns an iterator that gives us key and value.
If for some reason you only wanted the keys, you can use iterkeys:

mydict = { "a" : "Alpha", "b" : "Beta", "c" : "Charlie" }
for key in mydict.iterkeys():
print key, mydict[key]


Or if you wanted the values only, you can use itervalues:

mydict = { "a" : "Alpha", "b" : "Beta", "c" : "Charlie" }
for value in mydict.itervalues():
print value





Like Python? Here are some links to some more articles on Python:
  1. Little Python SQLite tutorial
  2. Little Python optparse module tutorial
  3. Little python dictionary hack

No comments: