Wednesday, 4 July 2018

Python | Create a dictionary with list comprehension in Python

In Python 2.6 and earlier, the dict constructor (dictionary ) 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)))

No comments:

Post a Comment

Thanks for your comments