파이썬 딕셔너리

데이터를 이름으로 바로 찾을 수 있어 빠르고 효율적으로 처리할 수 있다.

Key - Value 쌍을 데이터로 저장되며, 원하는 정보를 이름(Key)으로 빠르게 찾을 수 있고, Key에 매핑된 value를 바로 사용할 수 있는 자료형이다.

fruit_price = {"apple": 3000, "kiwi": 5000}
print(fruit_price["kiwi"]) #5000

선언 방식

dict1 = {}

student_scores = {
   "Math": 85,
   "Science": 92,
   "Reading": 78
}

dict2 = dict()

student_scores = dict(Math=85, Science=92, Reading=78)

get() 메서드

dict.get(”key”, “default”)

my_dict["k1"] = "saved value"
value = my_dict.get("k1", "default")
print(value)  # 출력: saved value

value = my_dict.get("k3", "default")
print(value)  # 출력: default
student_scores = dict(Math=85, Science=92, Reading=78)

keys() 메서드

my_dict = { "k1" : 1 , "k2" : 2}
keys = my_dict.keys()
print(keys)  # 출력: dict_keys(['k1', 'k2'])

values() 메서드

my_dict = {"k1": "v1", "k2": "v2" }
value = my_dict.pop("k1")
print(value)  # 출력: v1
print(my_dict)  # 출력: {'k2': 'v2'}

update() 메서드

my_dict = {"key1": "value1"}
my_dict.update({"key2": "value2", "key3": "value3"})
print(my_dict) # 출력: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

궁금증

dict1 = {}
for i in range(2):
    if "name" not in dict1:
        dict1["name"] = {"Apple"}  # 키가 없으면 새로운 집합(Set) 생성
    else:
        dict1["name"].add("Galaxy")  # 이미 존재하면 값 추가

    print(dict1)
#{'name': {'Apple'}}
#{'name': {'Galaxy', 'Apple'}}
import sys
input = sys.stdin.readline
dict1 = {"name": ["Happy"]}  # 문자열이 아닌 집합(Set)으로 초기화

for i in range(2):
    if "name" not in dict1:
        dict1["name"] = {"Apple"}  # 키가 없으면 새로운 집합(Set) 생성
    else:
        dict1["name"].append("Galaxy")  # 이미 존재하면 값 추가

    print(dict1)
#{'name': ['Happy', 'Galaxy']}
#{'name': ['Happy', 'Galaxy', 'Galaxy']}