딕셔너리는 기본적으로 중괄호를 이용하거나 혹은 dic() 함수를 이용하여 생성함.
my_dict = {"name":"Max", "age":28, "city":"New York"}
print(my_dict)
{'name': 'Max', 'age': 28, 'city': 'New York'}
# or use the dict constructor, note: no quotes necessary for keys
my_dict_2 = dict(name="Lisa", age=27, city="Boston")
print(my_dict_2)
{'name': 'Lisa', 'age': 27, 'city': 'Boston'}
my_dict = {"name":"Max", "age":28, "city":"New York"}
name_in_dict = my_dict["name"]
print(name_in_dict)
# KeyError if no key is found
# print(my_dict["lastname"])
Max
키를 추가한 후 추가한 키값에 값을 활당합니다. 접근 또한 키값을 이용하여 접근합니다.
my_dict = {"name":"Max", "age":28, "city":"New York"}
# add a new key
my_dict["email"] = "max@xyz.com"
print(my_dict)
{'name': 'Max', 'age': 28, 'city': 'New York', 'email': 'max@xyz.com'}
# or overwrite the now existing key
my_dict["email"] = "coolmax@xyz.com"
print(my_dict)
{'name': 'Max', 'age': 28, 'city': 'New York', 'email': 'coolmax@xyz.com'}
my_dict = {"name":"Max", "age":28, "city":"New York"}
# delete a key-value pair
del my_dict["email"]
# this returns the value and removes the key-value pair
print("popped value:", my_dict.pop("age"))
popped value: 28
# return and removes the last inserted key-value pair
# (in versions before Python 3.7 it removes an arbitrary pair)
print("popped item:", my_dict.popitem())
popped item: ('city', 'New York')
print(my_dict)
{'name': 'Max'}
# clear() : remove all pairs
# my_dict.clear()
my_dict = {"name":"Max", "age":28, "city":"New York"}
# use if .. in ..
if "name" in my_dict:
print(my_dict["name"])
Max
# use try except
try:
print(my_dict["firstname"])
except KeyError:
print("No key found")
No key found
my_dict = {"name":"Max", "age":28, "city":"New York"}
# loop over keys
for key in my_dict:
print(key, my_dict[key])
name Max
age 28
city New York
# loop over keys
for key in my_dict.keys():
print(key)
name
age
city
# loop over values
for value in my_dict.values():
print(value)
Max
28
New York
# loop over keys and values
for key, value in my_dict.items():
print(key, value)
name Max
age 28
city New York
딕셔너리의 참조값 복사 시 주의가 필요하다.
dict_org = {"name":"Max", "age":28, "city":"New York"}
# this just copies the reference to the dict, so be careful
dict_copy = dict_org
# now modifying the copy also affects the original
dict_copy["name"] = "Lisa"
print(dict_copy)
print(dict_org)
{'name': 'Lisa', 'age': 28, 'city': 'New York'}
{'name': 'Lisa', 'age': 28, 'city': 'New York'}
# use copy(), or dict(x) to actually copy the dict
dict_org = {"name":"Max", "age":28, "city":"New York"}
dict_copy = dict_org.copy()
# dict_copy = dict(dict_org)
# now modifying the copy does not affect the original
dict_copy["name"] = "Lisa"
print(dict_copy)
print(dict_org)
{'name': 'Lisa', 'age': 28, 'city': 'New York'}
{'name': 'Max', 'age': 28, 'city': 'New York'}
# Use the update() method to merge 2 dicts
# existing keys are overwritten, new keys are added
my_dict = {"name":"Max", "age":28, "email":"max@xyz.com"}
my_dict_2 = dict(name="Lisa", age=27, city="Boston")
my_dict.update(my_dict_2)
print(my_dict)
문자열이나 숫자와 같은 불변성을 가진 모든 유형을 키로 사용할 수 있다. 또한 튜플에 불변성을 가진 요소만 포함되어 있으면 딕셔너리의 키로 사용할 수 있다.
# use numbers as key, but be careful
my_dict = {3: 9, 6: 36, 9:81}
# do not mistake the keys as indices of a list, e.g my_dict[0] is not possible here
print(my_dict[3], my_dict[6], my_dict[9])
9 36 81
# use a tuple with immutable elements (e.g. number, string)
my_tuple = (8, 7)
my_dict = {my_tuple: 15}
print(my_dict[my_tuple])
# print(my_dict[8, 7])
15
# a list is not possible because it is not immutable
# this will raise an Error:
# my_list = [8, 7]
# my_dict = {my_list: 15}
중첩 딕셔너리 사용시 각각의 값들은 컨테이너 타입이 사용될 수 있다. (예: 리스트, 튜플, 딕셔너리)
my_dict_1 = {"name": "Max", "age": 28}
my_dict_2 = {"name": "Alex", "age": 25}
nested_dict = {"dictA": my_dict_1,
"dictB": my_dict_2}
print(nested_dict)
{'dictA': {'name': 'Max', 'age': 28}, 'dictB': {'name': 'Alex', 'age': 25}}
파이썬 - 문자열(Strings) (0) | 2021.02.16 |
---|---|
파이썬 - 집합(set) (0) | 2021.02.15 |
파이썬 - 튜플(tuple) 자료형 (0) | 2021.02.09 |
파이썬 - 리스트(list) 자료형 (0) | 2021.02.08 |
파이썬 - 문자열 포맷별 출력 (0) | 2020.12.30 |
댓글 영역