Assume mydict is a Python dictionary.
mydict = {'a': 1, 'b': 2}
I can use items to iterate its elements:
for k,v in mydict.items():
print k,v
Or use iteritems:
for k,v in mydict.iteritems():
print k,v
what’s the difference? I think the philosophy of python is ‘only one way to do’?
In Python 3 the
dict.iter...()methods have been removed and replace the normal ones.They existed as iterators were added into the language after dictionaries, so
dict.items()returns a list. Thedict.iter...()methods were added to allow people to make more efficient programs (as iterators are lazy), but also not break compatibility with old programs that expected a list.As Python 3 broke compatibility, this was fixed. (The old usage of
dict.iter()can be generated withlist(dict.iter()). Note that in Python 3dict.items()actually returns a dictionary view – which can be iterated over, but also provides other functionality.