티스토리 뷰
반응형
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How can I add new keys to a dictionary?
Dictionary에 새 키를 추가하는 방법
문제 내용
How do I add a key to an existing dictionary? It doesn't have an .add()
method.
기존 Dictionary에 키를 추가하려면 어떻게 해야 합니까? .add() 메서드가 없습니다.
높은 점수를 받은 Solution
You create a new key/value pair on a dictionary by assigning a value to that key
해당 키에 값을 할당하여 Dictionary에 새 키/값 쌍을 만듭니다.
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.
키가 존재하지 않으면 키가 추가되어 해당 값을 가리킵니다. 이 값이 있으면 가리키는 현재 값을 덮어씁니다.
가장 최근 달린 Solution
Adding keys to dictionary without using add
add를 사용하지 않고 Dictionary에 키 추가
# Inserting/Updating single value
# subscript notation method
d['mynewkey'] = 'mynewvalue' # Updates if 'a' exists, else adds 'a'
# OR
d.update({'mynewkey': 'mynewvalue'})
# OR
d.update(dict('mynewkey'='mynewvalue'))
# OR
d.update('mynewkey'='mynewvalue')
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
# To add/update multiple keys simultaneously, use d.update():
x = {3:4, 5:6, 7:8}
d.update(x)
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue', 3: 4, 5: 6, 7: 8}
# update operator |= now works for dictionaries:
d |= {'c':3,'d':4}
# Assigning new key value pair using dictionary unpacking.
data1 = {4:6, 9:10, 17:20}
data2 = {20:30, 32:48, 90:100}
data3 = { 38:"value", 99:"notvalid"}
d = {**data1, **data2, **data3}
# The merge operator | now works for dictionaries:
data = data1 | {'c':3,'d':4}
# Create a dictionary from two lists
data = dict(zip(list_with_keys, list_with_values))
출처 : https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary
반응형
'개발 > 파이썬' 카테고리의 다른 글
리스트에서 아이템의 인덱스 찾기 (0) | 2022.11.29 |
---|---|
exception처럼 numpy 경고 받기 (0) | 2022.11.29 |
리스트 안에 리스트가 있을 때 펼쳐서 일반 리스트로 만드는 방법 (0) | 2022.11.29 |
Dictionary를 value로 정렬하려면 어떻게 해야 합니까? (0) | 2022.11.29 |
'for' 루프의 인덱스 접근 (0) | 2022.11.29 |
댓글
공지사항
최근에 올라온 글