Created
May 11, 2015 03:44
-
-
Save shihpeng/940ebd1bd89ec3ff31ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In Python 2.6 and earlier, the dict constructor can receive an iterable of key/value pairs: | |
d = dict((key, value) for (key, value) in iterable) | |
# From Python 2.7 and 3 onwards, you can just use the dict comprehension syntax directly: | |
d = {key: value for (key, value) in iterable} | |
# Of course, you can use the iterable in any way you want (tuples and lists literals, generator comprehensions, list comprehensions, generator functions, functional composition... feel creative) as long as each element is an iterable itself of two elements: | |
d = {value: foo(value) for value in sequence if bar(value)} | |
def key_value_gen(k): | |
yield chr(k+65) | |
yield chr((k+13)%26+65) | |
d = dict(map(key_value_gen, range(26))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment