Python - Dictionary Comprehensions
Last Updated: 1734Z 23SEP19 (Created: 1734Z 23SEP19)

Create a new dictionary using a comprehension.

Signatures:

new_dict = {key:value for (key, value) in dictionary.items()}

Examples:

# Double each value in the dictionary
dict_1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
dict_2 = {k:v*2 for (k,v) in dict_1.items()}
print(dict_2)   # output: {'e': 10, 'b': 4, 'c': 6, 'a': 2, 'd': 8}

# Filter elements
user_email = {user.name:user.email for user in users if user.email}

References:

  1. Python Dictionary Comprehension