Home >Backend Development >Python Tutorial >How Can I Efficiently Create Dictionaries in Python?

How Can I Efficiently Create Dictionaries in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 14:35:11782browse

How Can I Efficiently Create Dictionaries in Python?

Creating Dictionaries with Comprehension

A dictionary can be constructed using list comprehension syntax, offering a concise approach to create dictionaries from a sequence of key-value pairs.

Using Dict Comprehension:

d = {key: value for key, value in zip(keys, values)}

Alternatives to Dict Comprehension:

  • Dict Constructor:
pairs = [('a', 1), ('b', 2)]
dict(pairs)                          # → {'a': 1, 'b': 2}
  • Dict Constructor with Dict Comprehension:
dict((k, v + 10) for k, v in pairs)  # → {'a': 11, 'b': 12}
  • Dict Constructor with Zip:
keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values))              # → {'a': 1, 'b': 2}

The above is the detailed content of How Can I Efficiently 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