티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to concatenate two dictionaries to create a new one?
두 개의 딕셔너리를 연결하여 새로운 딕셔너리를 만드는 방법은 무엇인가요?
문제 내용
Say I have three dicts
세 개의 딕셔너리가 있다고 가정하면
d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}
How do I create a new d4
that combines these three dictionaries? i.e.:
이 세 가지 딕셔너리를 결합한 새로운 d4를 어떻게 만들까요?
d4={1:2,3:4,5:6,7:9,10:8,13:22}
높은 점수를 받은 Solution
- Slowest and doesn't work in Python3: concatenate the
items
and calldict
on the resulting list: $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \ 'd4 = dict(d1.items() + d2.items() + d3.items())' 100000 loops, best of 3: 4.93 usec per loop
- Fastest: exploit the
dict
constructor to the hilt, then oneupdate
: $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \ 'd4 = dict(d1, **d2); d4.update(d3)' 1000000 loops, best of 3: 1.88 usec per loop
- Middling: a loop of
update
calls on an initially-empty dict: $ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \ 'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)' 100000 loops, best of 3: 2.67 usec per loop
- Or, equivalently, one copy-ctor and two updates:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \ 'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)' 100000 loops, best of 3: 2.65 usec per loop
1. 가장 느리고 Python3에서 작동하지 않는 방법은 아이템을 연결하고 결과 목록에 dict를 호출하는 것입니다.
3. 가장 빠른 방법은 dict 생성자를 이용하여 하나의 업데이트를 수행하는 것입니다.
5. 중간에 있는 방법은 처음에 비어있는 딕셔너리에서 업데이트 호출의 반복문입니다.
7. 또는 복사-생성자 하나와 업데이트 두 개:
I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).
저는 접근법 (2)를 권장하며 (1)은 피하는 것이 좋습니다. 또한 아이템의 연결된 목록에 대한 O(N)의 추가 보조 메모리도 사용합니다.
가장 최근 달린 Solution
Use the dict constructor
dict 생성자를 사용하십시오.
d1={1:2,3:4}
d2={5:6,7:9}
d3={10:8,13:22}
d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))
As a function
함수로 사용하는 경우
from functools import partial
dict_merge = partial(reduce, lambda a,b: dict(a, **b))
The overhead of creating intermediate dictionaries can be eliminated by using thedict.update()
method:
중간에 있는 딕셔너리 생성의 오버헤드를 제거하기 위해 dict.update() 메서드를 사용할 수 있습니다.
from functools import reduce
def update(d, other): d.update(other); return d
d4 = reduce(update, (d1, d2, d3), {})
출처 : https://stackoverflow.com/questions/1781571/how-to-concatenate-two-dictionaries-to-create-a-new-one
'개발 > 파이썬' 카테고리의 다른 글
Windows에서 tkinter를 pip 또는 easy_install로 설치하기 (0) | 2023.02.19 |
---|---|
pip를 사용하여 Scipy 설치할 때 오류 수정하기 (0) | 2023.02.19 |
파이썬에서 문자열을 파일로 래핑하기 (0) | 2023.02.18 |
'sphinx-build fail - autodoc can't import/find module' 오류 수정하기 (0) | 2023.02.17 |
문자열에서 Pandas DataFrame 만들기 (0) | 2023.02.17 |