Dictionary
์ฌ๋์ ๋๊ตฌ๋ ์ง โ์ด๋ฆโ = โํ๊ธธ๋โ, โ์์ผโ = โ๋ช ์ ๋ช ์ผโ ๋ฑ์ผ๋ก ๊ตฌ๋ถ ํ ์ ์๋ค. ํ์ด์ฌ์ ์๋ฆฌํ๊ฒ๋ ์ด๋ฌํ ๋์ ๊ด๊ณ๋ฅผ ๋ํ๋ผ ์ ์๋ ์๋ฃํ์ ๊ฐ์ง๊ณ ์๋ค. ์์ฆ ์ฌ์ฉํ๋ ๋๋ถ๋ถ์ ์ธ์ด๋ค๋ ์ด๋ฌํ ๋์ ๊ด๊ณ๋ฅผ ๋ํ๋ด๋ ์๋ฃํ์ ๊ฐ๊ณ ์๋๋ฐ, ์ด๋ฅผ ์ฐ๊ด ๋ฐฐ์ด(Associative array) ๋๋ ํด์(Hash)๋ผ๊ณ ํ๋ค.
ํ์ด์ฌ์๋ ์ด ์๋ฃํ์ ๋์ ๋๋ฆฌ๋ผ๊ณ ํ๋๋ฐ, ๊ธฐ๋ณธ์ ์ผ๋ก Key, Value ๋ผ๋ ๊ฒ์ ํ ์์ผ๋ก ๊ฐ๋ ์๋ฃํ์ด๋ค. ๋์ ๋๋ฆฌ๊ฐ ํํ์ด๋ ๋ฆฌ์คํธ์ ๊ฐ์ฅ ๋ค๋ฅธ ์ ์ด๋ผ๋ฉด, ์์ฐจ์ ์ผ๋ก ํด๋น ์์๊ฐ์ ๊ตฌํ์ง ์๊ณ Key ๋ฅผ ํตํด Value๋ฅผ ์ป๋๋ค๋ ์ ์ด๋ค. ์ฒ์๋ถํฐ ๋ค ๋ค์ ธ๋ณด๋ ๊ฒ์ด ์๋๊ณ , Key๊ฐ ์๋ ๊ณณ๋ง ํ์ํ๋ค๋ ๊ฒ์ด๋ค.
Key list
>>> a = {โnameโ: โpeyโ, โphoneโ: โ0119993323โ, โbirthโ: โ1118โ}
>>> a.keys()
dict_keys([โnameโ, โphoneโ, โbirthโ])
Items
>>> a.items()
dict_items([(โnameโ, โpeyโ), (โphoneโ, โ0119993323โ), (โbirthโ, โ1118โ)])
items ํจ์๋ key์ value์ ์์ ํํ๋ก ๋ฌถ์ ๊ฐ์ dict items ๊ฐ์ฒด๋ก ๋๋ ค์ค๋ค.
Get
Key ๋ก Value ๋ฅผ ์ป์ด๋ณด์.
>>> a = {โnameโ:โpeyโ, โphoneโ:โ0119993323โ, โbirthโ: โ1118โ}
>>> a.get(โnameโ)
โpeyโ
>>> a.get(โphoneโ)
โ0119993323โ
์ ์ธ ๋ฐฉ๋ฒ / Value ์ ๊ทผ
# ์ ์ธ
author = {"python" : "person1", "c++" : "person2"}
# ์ ๊ทผ
author["python"]
# ์ญ์
del author["python"]
# ์ถ๊ฐ
author["python"] = "person1"
for item in author:
print(item, "is designed by ", author[item])
c++ is designed by person2
python is designed by person1
์ค์ต
Example 1
(a) ๋ค์๊ณผ ๊ฐ์ด list ํ๋๋ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๋ฅผ, ๋ค๋ฅธ list๋ ์ธ์ด์ ๊ฐ๋ฐ์ ์ด๋ฆ์ ๊ฐ๋๋ก ์ ์ธํฉ๋๋ค.
language = ["python", "c++", "javascript", "go"]
author = ["Guido van Rossum", "Bjarne Stroustrup", "Brendan Eich", "Robert Griesemer"]
(b) ํจ์ matingPairs()๋ฅผ ๋ง๋๋๋ฐ, ์ ๋ ฅ ํ๋ผ๋ฉํ๋ก ์์ ๋ ๋ฆฌ์คํธ๋ฅผ ๋ฐ์์, ๊ฒฐ๊ณผ๋กค set ํ์ ์ ๋๋ ค์ค๋๋ค.
(c) ํจ์ matingPairs()๋ ๋ ๋ฆฌ์คํธ์์ ๊ฐ๊ฐ ํ๋์ ๊ฐ์ ๊บผ๋ด์ ์ธ์ด ์ด๋ฆ๋ณ ์ ์์ tuple์ ๋ง๋ ํ,
(d) ํจ์ matingPairs() ์์ ๋ด๋ถ ๋ณ์์ธ set ํ์ ๋ฐ์ดํฐ ํ์ ์ (c)์์ ๋ง๋ tuple์ ์์ดํ ์ผ๋ก ์ถ๊ฐํด ์ค๋๋ค.
(e) ๋ชจ๋ ์ธ์ด์ ๋ํ ์ ์ ๋งคํ๊ณผ, ์ด๋ฅผ set์ ๋ฃ๋ ๊ณผ์ ์ ๋ง์น๋ฉด, ํจ์ matingPairs()์ ๊ฒฐ๊ณผ๊ฐ์ผ๋ก set๋ฅผ ๋๋ ค์ค๋๋ค.
(f) ํจ์ matingPairs()์ ๊ฒฐ๊ณผ๊ฐ์ ํ๋ฉด์ ์ถ๋ ฅํฉ๋๋ค.
language = ["python", "c++", "javascript", "go"]
author = ["Guido van Rossum", "Bjarne Stroustrup", "Brendan Eich", "Robert Griesemer"]
def matingPairs(array1, array2):
result_set = set()
for i in range(len(array1)):
temp_tuple = (array1[i], array2[i])
result_set.add(temp_tuple)
return result_set
matingPairs(language, author)
{('c++', 'Bjarne Stroustrup'),
('go', 'Robert Griesemer'),
('javascript', 'Brendan Eich'),
('python', 'Guido van Rossum')}
Example 2
๋ค์์ ์๊ตฌ ์ฌํญ์ ๋ง๋ ํ๋ก๊ทธ๋จ์ ๊ฐ๋ฐํ์ฌ ์๋์ ์ ๋ ฅ์ฐฝ์ ํตํด์ ์คํํฉ๋๋ค.
(a) dictionary
์ key
๋ ์ ์ผํด์ผ ํ์ง๋ง value
๋ ์ ์ผํ์ง ์์๋ ๋ฉ๋๋ค.
(b) count_values()
๋ผ๋ ์ด๋ฆ์ ํจ์๋ฅผ ๊ตฌํํฉ๋๋ค.
(c) count_values()
ํจ์๋ ํ๋์ dictionary๋ฅผ ์
๋ ฅ ํ๋ผ๋ฉํ๋ก ๋ฐ์์, ์ด dictionary๊ฐ ํฌํจํ ์๋ก ๋ค๋ฅธ value์ ๊ฐ์๋ฅผ ๋ฐํํฉ๋๋ค.
(d) ์๋ฅผ ๋ค์ด, {'red': 1, 'green': 1, 'blue': 2}
๊ฐ ์
๋ ฅ ํ๋ผ๋ฉํ๋ก ์ ๋ฌ๋๋ฉด, 2๋ฅผ ๋ฐํํฉ๋๋ค.
def count_values(dic):
set_dic = set()
for item in dic:
set_dic.add(dic[item])
return len(set_dic)
dic = {'red' : 1, 'green' : 1, 'blue' : 2}
count_values(dic)
2