Home >Backend Development >Python Tutorial >Can List Comprehension Create Dictionaries in Python?

Can List Comprehension Create Dictionaries in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 12:23:091028browse

Can List Comprehension Create Dictionaries in Python?

Creating a Dictionary with Comprehension

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn