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

python, python-3.x

Solution

values() version of Just another dunce's answer

for value in (mydict[key] for key in mydict):

or

def dict_values(d):
   return (mydict[key] for key in mydict)

def dict_items(d):
   return ((key, mydict[key]) for key in mydict)

for value in dict_values(mydict):
    ...

for value in dict_items(mydict):
    ...

This is pretty crappy though. You could check the python version and instead of returning the generator, return `d.items()` or `d.iteritems()` as appropriate

I think a better question may be how to write Python2 code that works well with 2to3 and generates good Python3 code

Problem

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?

Original source