파이썬

[python] 사전에 새 키를 어떻게 추가합니까?

zooheon 2022. 8. 21. 23:01
반응형

기존 사전에 키를 어떻게 추가합니까? 방법 이 없습니다 .add().

 

해당 키에 값을 할당하여 사전에 새 키/값 쌍을 만듭니다.

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

키가 없으면 키가 추가되고 해당 값을 가리킵니다. 존재하는 경우 가리키는 현재 값을 덮어씁니다.

 

여러 키를 동시에 추가하려면 다음을 사용 dict.update()하십시오.

>>> x = {1:2}
>>> print(x)
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print(x)
{1: 2, 3: 4, 5: 6, 7: 8}

단일 키를 추가하는 경우 허용되는 답변은 계산 오버헤드가 적습니다.

 

Python 사전에 대한 정보를 통합하고 싶습니다.

빈 사전 만들기

data = {}
# OR
data = dict()

초기 값으로 사전 만들기

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

단일 값 삽입/업데이트

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

여러 값 삽입/업데이트

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

파이썬 3.9 이상:

업데이트 연산자 |=이제 사전에서 작동합니다.

data |= {'c':3,'d':4}

원본을 수정하지 않고 병합된 사전 만들기

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

파이썬 3.5 이상:

이것은 사전 압축 풀기 라는 새로운 기능을 사용합니다 .

data = {**data1, **data2, **data3}

파이썬 3.9 이상:

이제 병합 연산자 | 가 사전에서 작동합니다.

data = data1 | {'c':3,'d':4}

사전에서 항목 삭제

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

키가 이미 사전에 있는지 확인

key in data

사전의 쌍을 통해 반복

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

두 목록에서 사전 만들기

data = dict(zip(list_with_keys, list_with_values))

 

반응형