5 ms·
In Python 3.3: Iterate over keys: "for k in d.keys()" ...over values: "for v in d.values()" ...over both: "for k, v in d.items()"
by cardamomo 14y ago
In Python 3.3:
Iterate over keys: "for k in d.keys()"
...over values: "for v in d.values()"
...over both: "for k, v in d.items()"
- textminer 14y agoLove it. It's that way with range, too, right? Does one end up casting things to lists more often if so much is naturally an iterator?
- pyre 14y agohttp://www.python.org/dev/peps/pep-3106/ http://www.python.org/dev/peps/pep-3106/ The original plan was to simply let .keys(), .values() and .items() return an iterator, i.e. exactly what iterkeys(), itervalues() and iteritems() return in Python 2.x. However, the Java Collections Framework [1] suggests that a better solution is possible: the methods return objects with set behavior (for .keys() and .items()) or multiset (== bag) behavior (for .values()) that do not contain copies of the keys, values or items, but rather reference the underlying dict and pull their values out of the dict as needed.
- andreasvc 14y ago"for k in d" is even shorter. I wonder what they point of the .keys() method is actually, perhaps it's just as redundant as .has_key(). Most times you can iterate over the dictionary itself; when you need to explicitly pass an iterator or list, iter(d) or list(d) is shorter than d.keys().
- andrevoget 14y agoIf you iterate over .keys(), you are allowed to use del key[value].
- andreasvc 14y agoOnly in Python 2, which returns something to the effect of list(dict); so my point remains, they keys method doesn't add anything which you don't get (more explicitly) by coercing to a list when needed.