Wednesday, May 2, 2012

Generators to iterate over a dictionary uniformly in both Python 2 and 3

Is there a way to efficiently iterate over the values/items in a dictionary that works in both Python 2 and Python 3?



In Python 2, I can write



for x in mydict:
for x in mydict.iterkeys():
for x in mydict.viewkeys():
for x in mydict.itervalues():
for x in mydict.viewvalues():
for x in mydict.iteritems():
for x in mydict.viewitems():


and in Python 3, I have the following possibilities:



for x in mydict:
for x in mydict.keys():
for x in mydict.values():
for x in mydict.items():


So, I can iterate over the keys with for x in mydict, and that works in both Python 2 and 3. But is there a way to iterate over values and key-value pairs ('items') that works universally? I need it for writing Python code that can be run in both Python versions.



(On a side note, other obstacles with iterators can be bypassed easily; take for example:



if sys.version_info.major<3:
from itertools import izip as zip, imap as map


However, the dictionary methods cannot be redefined easily like map and zip.)



Any ideas?





No comments:

Post a Comment