Python dictionary comprehension

You can create a dctionary from a list by so-called dictionary comprehension.

a = [2, 5, 8]
d = {n: n + 1 for n in a}

print(d)  # {2: 3, 5: 6, 8: 9}

The n is the "local" variable iterating a. n is a key and n + 1 is a value in the new generated dictionary. This style is called "dictionary comprehension" in Python PEP 274. It is like list comprehension. Without this one-liner expression, you should write the multiple-line codes in the for statement.

Example: Get the pairs of the words and lengths

a = ['Apple', 'Microsoft', 'Google']
d = {i: len(i) for i in a}

print(d)  # {'Apple': 5, 'Microsoft': 9, 'Google': 6}

Python dictionary comprehension is an expression that iterating elements in the original list. i is a key and the length of it is a value in the new dictionary.

Create a dictionary from the dictionary with Python dictionary comprehension

The following example shows creating new dictionary from old dictionary in one-liner expression.

a = {'x': 5, 'y': 7}
d = {k: v ** 2 for k, v in a.items()}

print(d)  # {'x': 25, 'y': 49}

If you want to iterate a dictionary, use items() in loop.

Python Dictionary

Python Tutorial