Re:Hidden features of Python
by theli0nheart on Tuesday July 13, 2010 @07:06PM
(#1513043)
My favorite feature (just released in Python 2.7, already in P3K) are dictionary comprehensions. E.g., you can now do:
[ Parent
| on HN ]
In 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}Pre 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}
Re:Hidden features of Python
by calibraxis on Wednesday July 14, 2010 @03:44AM
(#1513961)
Thank you very much! Lack of simple dict-building had been bothering me.
map-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.