Given the following dict :
>>> d {'a': 1, 'c': 3, 'b': 2}
You can simply iterate over the keys like this:
>>> for k in d: ... print(k, d[k]) ... ('a', 1) ('c', 3) ('b', 2)
This implicitly calls the special __iter__() method, but remember:
Explicit is better than implicit.
Python 2.x
What do you expect from a refund?
>>> tuple(d.iter())
Too ambiguous, perhaps?
Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'iter'
This seems like a reasonable approach.
What if you want to iterate over only the keys?
>>> tuple(d.iterkeys()) ('a', 'c', 'b')
Nice! And the meanings?
>>> tuple(d.itervalues()) (1, 3, 2)
What about keys and values ββin the form of pairs (tuples)?
>>> tuple(d.iteritems()) (('a', 1), ('c', 3), ('b', 2))
Python 3.x
Things are a little different , objects returned by dict.keys() , dict.values() and dict.items() , view objects . They can be used in much the same way:
>>> tuple(d.keys()) ('a', 'c', 'b') >>> tuple(d.values()) (1, 3, 2) >>> tuple(d.items()) (('a', 1), ('c', 3), ('b', 2))