본문 바로가기

python

파이썬 딕셔너리 {dictionary} 기능 모음

1️⃣ 딕셔너리는 키(key)와 밸류(value)의 쌍으로 이루어진 자료의 모임이다. 

person = {"name":"Bob", "age": 21}
print(person["name"])                                  #Bob

 

2️⃣ 딕셔너리를 만드는 데는 여러가지 방법을 쓸 수 있다.

a = {"one":1, "two":2}

# 빈 딕셔너리 만들기
a = {}
a = dict()

 

3️⃣ 딕셔너리의 요소에는 순서가 없기 때문에 인덱싱을 사용할 수 없다.

person = {"name":"Bob", "age": 21}
print(person[0])                                     # 0이라는 key가 없으므로 KeyError 발생!

 

4️⃣ 딕셔너리의 값을 업데이트하거나 새로운 쌍의 자료를 넣을 수 있다.

person = {"name":"Bob", "age": 21}

person["name"] = "Robert"
print(person)                                              # {'name': 'Robert', 'age': 21}

person["height"] = 184.8
print(person)                                          # {'name': 'Robert', 'age': 21, 'height': 184.8}

 

5️⃣ 딕셔너리의 밸류로는 아무 자료형이나 쓸 수 있고, 다른 딕셔너리를 넣을 수도 있다!

person = {"name":"Alice", "age": 16, "scores": {"math": 81, "science": 92, "Korean": 84}}
print(person["scores"])                                   # {'math': 81, 'science': 92, 'Korean': 84}
print(person["scores"]["science"])                   # 92

 

6️⃣ 딕셔너리 안에 해당 키가 존재하는지 알고 싶을 때는 in을 사용한다.

person = {"name":"Bob", "age": 21}

print("name" in person)                    # True
print("email" in person)                     # False
print("phone" not in person)               # True

 

7️⃣ 리스트와 딕셔너리의 조합

딕셔너리는 리스트와 함께 쓰여 자료를 정리하는 데 쓰일 수 있다.

people = [{'name': 'bob', 'age': 20}, {'name': 'carry', 'age': 38}]

# people[0]['name']의 값은?            'bob'
# people[1]['name']의 값은?            'carry'

person = {'name': 'john', 'age': 7}
people.append(person)

# people의 값은? [{'name':'bob','age':20}, {'name':'carry','age':38}, {'name':'john','age':7}]
# people[2]['name']의 값은? 'john'

 

 

8️⃣ smith의 science 점수 출력