티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Add a new item to a dictionary in Python

Python에서 딕셔너리에 새 항목 추가

 문제 내용 

How do I add an item to an existing dictionary in Python? For example, given:

기존 파이썬 딕셔너리에 새 항목을 추가하는 방법은 무엇인가요? 예를 들어, 다음과 같은 딕셔너리가 주어졌을 때:
default_data = {
    'item1': 1,
    'item2': 2,
}

 

I want to add a new item such that:

새 항목을 추가하려면 다음과 같이 하고 싶습니다:
default_data = default_data + {'item3': 3}

 

 

 높은 점수를 받은 Solution 

default_data['item3'] = 3

 

Easy as py.

Python에서는 간단합니다.

 

Another possible solution:

다른 가능한 해결책:
default_data.update({'item3': 3})

 

which is nice if you want to insert multiple items at once.

만약 한 번에 여러 항목을 삽입하려는 경우에는 유용합니다.

 

 

 

 가장 최근 달린 Solution 

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work:

추가로, 딕셔너리에 대한 + 연산자를 구현하는 방법을 묻는 것이었다면, 다음과 같이 작성할 수 있습니다.
>>> class Dict(dict):
...     def __add__(self, other):
...         copy = self.copy()
...         copy.update(other)
...         return copy
...     def __radd__(self, other):
...         copy = other.copy()
...         copy.update(self)
...         return copy
... 
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}

 

Note that this is more overhead then using dict[key] = value or dict.update(), so I would recommend against using this solution unless you intend to create a new dictionary anyway.

하지만 이 방법은 dict[key] = value 또는 dict.update()를 사용하는 것보다 더 많은 오버헤드가 발생하므로 새로운 딕셔너리를 생성할 경우를 제외하고는 사용하지 않는 것이 좋습니다.

 

 

 

출처 : https://stackoverflow.com/questions/6416131/add-a-new-item-to-a-dictionary-in-python

반응형
댓글
공지사항
최근에 올라온 글