by delluminatus · 11y ago · 0 comments
dict([n, 2 ** n] for n in range(5))
But they pointed out an actual "dict comprehension" that I didn't even realize existed: { n: n ** 2 for n in range(5) }
And there is a similar "set comprehension": { n ** 2 for n in range(5) }
Always amazes me how you can use Python for so many years and still encounter new features in the language. a = (i for i in range(10) if i % 2 == 0)
print(list(a))
You can omit the parenthesis, and use them in calls which expect an iterable. b = max(i for i in range(0, 10) if i % 2 == 0)
print(b)With the dictionary comprehension you can just separate the key and value with a colon, which is more natural. It might just be sugar on top of a generator expression but it is definitely a special case, syntactically speaking.
s = {i**2 for i in range(10) if i}
and the colon is what makes the dict comprehension different from the set comprehension: d - {i:i**2 for i in range(10) if i}Here's how you make those set/dict whatever comprehensions in Python 2.6, before the native syntax is used:
s = set(i for i in xrange(10) if not i%2)Look for dictorsetmaker (for {}) testlist_comp (for generator expressions) and listmaker (for [], i.e. list comprehensions).
>>> dict([n, 2 n] for n in range(5)) {0: 1, 1: 2, 2: 4, 3: 8, 4: 16} >>> { n: n 2 for n in range(5) } {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}