"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > How Can I Efficiently Create Dictionaries Using Python Comprehension?

How Can I Efficiently Create Dictionaries Using Python Comprehension?

2025-03-25에 게시되었습니다
검색:632

How Can I Efficiently Create Dictionaries Using Python Comprehension?

Python Dictionary Comprehension

In Python, dictionary comprehensions offer a concise way to generate new dictionaries. While they are similar to list comprehensions, there are some notable differences.

Key-Only Dictionary Comprehension

Unlike the question suggests, you cannot create a dictionary comprehension for the keys. You must explicitly specify the keys and values. For example:

d = {n: n**2 for n in range(5)}

This creates a dictionary with keys from 0 to 4 and values equal to the square of the corresponding key.

Setting a Single Value for Multiple Keys

To set the same value for multiple keys, you can use the following syntax:

d = {n: True for n in range(5)}

This creates a dictionary with keys from 0 to 4, all with the value True.

Setting Multiple Values for Multiple Keys

As the question points out, it is not possible to specify multiple values for the same key using a dictionary comprehension. To achieve this, you can either manually assign values using a loop or create a separate dictionary and update the existing one using update():

# Create a new dictionary
new_dict = {n: n for n in range(5)}

# Update the existing dictionary
existing_dict.update(new_dict)
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3