5 ms·
My favorite feature (just released in Python 2.7, already in P3K) are dictionary comprehensions. E.g., you can now do: >>> {s: len(s) for s in ["one", "two
by theli0nheart 16y ago
My favorite feature (just released in Python 2.7, already in P3K) are dictionary comprehensions. E.g., you can now do:
>>> {s: len(s) for s in ["one", "two", "three"]
{"one": 3, "two": 3, "three": 5}
- mkramlich 16y agomore like new feature rather than hidden feature. but agreed, it's very cool
- twism 16y agoIn python land (Django) for the past couple of months and I've been loving it, just thought this was a good excuse to fire up slime. In clojure... (defn map-comprehension [f sequence] (reduce #(assoc %1 %2 (f %2)) {} sequence)) usage: user> (map-comprehension count ["one" "two" "three"]) {"three" 5, "two" 3, "one" 3}
- snprbob86 16y agoPre 2.7, you can just give the dict constructor a generator of tuples: >>> dict((s, len(s)) for s in ["one", "two", "three"]) {'three': 5, 'two': 3, 'one': 3}
- calibraxis 16y agoThank you very much! Lack of simple dict-building had been bothering me.
- omaranto 16y agomap-comprehension is a bad name for that function, since it doesn't give you comprehension-like syntax, instead it is just a function that behaves like map but produces a map instead of another sequence. I'd call it map-map.