Python’s Dictionary Comprehension Makes It Easy
The Python language is known for its readability and ease of use, making it an excellent choice for technical authoring. With the release of version 3.7, Python now supports dictionary comprehensions, …
The Python language is known for its readability and ease of use, making it an excellent choice for technical authoring. With the release of version 3.7, Python now supports dictionary comprehensions, a feature that can be used to create dictionaries from lists in a more efficient way than traditional methods.
new_dictionary = {key: value for item in list if condition}
The “key” and “value” are expressions that refer to an element in the list and can be any kind of expression. The “for item in list” part loops over elements in the provided list, and the “if condition” is optional and only creates a key-value pair if the condition returns True for an individual element.
The following example demonstrates how to create a dictionary from a list of names:
names = ['John', 'Mary', 'Alex']
name_dict = {name: len(name) for name in names}
print(name_dict) # Outputs: {'John': 3, 'Mary': 4, 'Alex': 5}
In this code, the dictionary comprehension creates a new dictionary where each key is a string from the list “names”, and its corresponding value is the length of that string.
This feature is not only useful for creating dictionaries from lists but also for any other mapping processes in Python programming.