딕셔너리(dictionary)


- 중괄호로 선언
- '키: 값' 형대를 쉼표로 연결하여 만듦
list = [1, 2, 3, 4, "문자"]
dict_a = {
"name": "어벤저스 엔드게임",
"type": "히어로 무비"
}
print(dict_a["name"])
print(dict_a["type"])

# P163 예제
dictionary = {
"name": "7D 건조 망고",
"type": "당절임",
"ingredient": ["망고", "설탕", "메타중아황산나트룸", "치자황색소"],
"origin": "필리핀"
}
print("name:", dictionary["name"])
print("type:", dictionary["type"])
print("ingredient:", dictionary["ingredient"])
print("origin:", dictionary["origin"])
print()
dictionary["name"] = "8D 건조 망고"
print("name:", dictionary["name"])
print("ingredient:", dictionary["ingredient"][1])

name = "문자"
age = "나이"
dictionary = {
name: 1,
age: 0
}
print(dictionary)
dictionary["뉴키"] = 100
print(dictionary)
dictionary[age] = 60
print(dictionary)
del dictionary[name]
print(dictionary)

딕셔너리 내부 키 확인
# P168 예제
dictionary = {
"name": "7D 건조 망고",
"type": "당절임",
"ingredient": ["망고", "설탕", "메타중아황산나트룸", "치자황색소"],
"origin": "필리핀"
}
key = input("> 접근하고자 하는 키를 입력: ")
if key in dictionary :
print("키: {}, 값: {}".format(key, dictionary[key]))
else :
print("존재하지 않는 키를 입력하셨습니다.")

for 반복문과 딕셔너리
for 키 변수 in 딕셔너리 : # 키 값이 변수에 들어간다
코드
# P170 예제
dictionary = {
"name": "7D 건조 망고",
"type": "당절임",
"ingredient": ["망고", "설탕", "메타중아황산나트룸", "치자황색소"],
"origin": "필리핀"
}
for key in dictionary :
print("{} : {}".format(key, dictionary[key]))

ex) P172, 3번
# P172, 3번
numbers = [1, 2, 6, 8, 4, 3, 2, 1, 9, 5, 4,
9, 5, 4, 9, 7, 2, 1, 3, 5 ,4, 8, 9, 7, 2, 3
]
counter = {}
for number in numbers : # 리스트 numbers 요소를 number에 넣는다
if number in counter : # 딕셔너리 counter에 요소 number가 있으냐
counter[number] = counter[number] + 1 # 있으면 증가
else :
counter[number] = 1 # 없으면 딕셔너리 키 값(number) 넣고 1 초기값
print(counter)
