Question: Is it possible to leverage list comprehension to establish a dictionary?
Scenario: Creating a dictionary by iteratively traversing key-value pairs using list comprehension, expressed as d = {... for k, v in zip(keys, values)}.
Solution:
In Python 2.7 and later versions, you can utilize a dictionary comprehension, expressed as {key: value for key, value in zip(keys, values)}.
Alternatively, you can employ the dict constructor:
pairs = [('a', 1), ('b', 2)] a = dict(pairs) # Results in {'a': 1, 'b': 2} b = dict((k, v + 10) for k, v in pairs) # Results in {'a': 11, 'b': 12}
If you have two distinct lists, keys and values, you can use the dict constructor in conjunction with zip:
keys = ['a', 'b'] values = [1, 2] c = dict(zip(keys, values)) # Results in {'a': 1, 'b': 2}
The above is the detailed content of Can List Comprehension Create Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!