๋ชฉ์ฐจ
ํ์ด์ฌ์ dictionary๋ฅผ ๋ค๋ฃจ๋ ๋์ค
2๊ฐ์ dictionary๋ฅผ ํฉ์น๋ ๋ฐฉ๋ฒ์ ๋ํด์ ๊ณต๋ถํด๋ณด์๋ค!
1. key๊ฐ์ด ๊ฒน์น์ง ์์ ๋
dict_1 = {'A':1, 'B':2, 'C':3}
dict_2 = {'D':1, 'E':2, 'F':3}
- update()
result = dict_1
result.update(dict_2)
>>> {'A': 1, 'B': 2, 'C': 3, 'D': 1, 'E': 2, 'F': 3}
dictnary์ ๋ฉ์๋ ์ค ํ๋์ธ update๋ฅผ ์ด์ฉํ๋ฉด
์์ ๊ฐ์ด ๋ ๊ฐ๋ฅผ ํฉ์น ์ ์๋ค.
์ด๋, key๊ฐ์ด ๋ชจ๋ ๊ฒน์น์ง ์์์ผ ํ๋ค๋ ์ ์ ์กฐ๊ฑด์ด ์๋ค.
๋ง์ฝ ๊ฒน์น๋ค๋ฉด,
์ค๋ณต๋ ๊ธฐ์กด key๊ฐ์ update์ ์ธ์๋ก ๋ฃ์ด์ค ๊ฐ์ผ๋ก ๋์ฒด๋๋ค.
2. key๊ฐ์ด ๊ฒน์น ๋
๋ฐ์ดํฐ๋ฅผ ๋์ ๋๋ฆฌ๋ก ์ฒ๋ฆฌํ ๋
์๋ก์ด ๊ฒฐ๊ณผ๋ฅผ ์ถ๊ฐํ๊ณ ์ถ์ ๊ฒฝ์ฐ
์ด ๋ฐฉ๋ฒ์ ํ์ฉ์ ํ ์ ์์ ๊ฒ์ด๋ค!
- Counter
ํ์ด์ฌ์์ ์ง์ํ๋ collections ๋ชจ๋์๋
Counter๋ผ๋ ๊ฐ์ฒด๊ฐ ์๋ค.
์ด๋ฅผ ์ด์ฉํด๋ณด์!
dict_1 = {'A':1, 'B':2, 'C':3}
dict_2 = {'A':1, 'D':2, 'C':3}
from collections import Counter
result = dict(Counter(dict_first)+Counter(dict_second))
result
>>> {'A': 2, 'B': 2, 'C': 6, 'D': 4}
Counter๋ฅผ ์ด์ฉํ์ฌ ๋ dictionary ๊ฐ๊ฐ์ ์์๋ค์ ์๋ฅผ ์ธ์ด์ค ๋ค
ํฉ์ณ์ฃผ๋ ๋ฐฉ์์ผ๋ก ํด๊ฒฐ์ ํด๋ณด์๋ค!
์กฐ๊ฑด์ ํ์ฉํ๋ ๋ฐฉ์
Counter๋ฅผ ์ด์ฉํ์ง ์๊ณ ์กฐ๊ฑด๋ฌธ์ ํตํด
ํด๊ฒฐ์ ํด๋ณด์๋ค.
result = dict_1
temp = list(dict_2.keys())
for i in range(len(dict_2)):
if temp[i] in result:
result[temp[i]] += dict_2[temp[i]]
else:
result[temp[i]] = dict_2[temp[i]]
result
>>> {'A': 2, 'B': 2, 'C': 6, 'D': 4}
'๐ | Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] collections ๋ชจ๋ (0) | 2023.01.05 |
---|---|
Python_Call by Object Reference (0) | 2022.01.18 |
Python_๋ฌธ์์ด ๋ค์ง๊ธฐ (0) | 2022.01.17 |
ํ์ด์ฌ ๋ฌธ๋ฒ ๊ณต๋ถ (0) | 2021.08.29 |
๋๊ธ