4 ms·
Love defaultdict. It and dict/set/list compressions are a big part of what makes Python so fast to write in. Great practice for 2.7 that's probably quashed in
by textminer 14y ago
Love defaultdict. It and dict/set/list compressions are a big part of what makes Python so fast to write in.
Great practice for 2.7 that's probably quashed in 3.0. For large dicts, no need to create a giant set en route when iterating over keys, values, or both. Use "for k in d.iterkeys()", "for v in d.itervals", "for k,v in d.iteritems."
While I'm at it-- if you're ever finding yourself using a huge amount of awfully rigid objects from a single class, use __slots__ to allocate needed variables! Python will otherwise define the object's namespace in a dict (called __dict__) which allocates a whole kilobyte per object. Bad news if you have several hundred thousand... Guessing this is why Guido loves namedtuples so much for basic attributed storage.
- cardamomo 14y agoIn 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.