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

How Can I Efficiently Create Dictionaries in Python?

Susan Sarandon
Release: 2024-12-28 14:35:11
Original
787 people have browsed it

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)}
Copy after login

Alternatives to Dict Comprehension:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template