[TIL. 14]Python-Dictionary

신지원·2021년 3월 8일
0

Python

목록 보기
3/14
post-thumbnail

딕셔너리란?

사람은 누구든지 "이름" = "홍길동", "생일" = "몇 월 며칠" 등으로 구별할 수 있다. 파이썬에서 이러한 대응 관계를 나타낼 수 있는 자료형을 딕셔너리라고 한다.

딕셔너리는 리스트나 튜플 처럼 순차적으로 해당 요소값을 구하지 않고 key를 통해 value를 얻는다. 즉, 하나의 값을 찾기 위해서 모든 요소를 순차적으로 검색할 필요 없이 딱 원하는 곳을 지정해서 찾을 수 있다.

기본

# {key:value} 기본모형
menu = {"avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}


# empty dictionary
empty_dic = {}


# Key 추가하기
# dictionary[key] = value
menu = {"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2}
menu["cheesecake"] = 8

print(menu) # {"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2, "cheesecake": 8}

# 여러개의 key 추가하기 (.update())
# dictionary.update({key:value,key:value,key:value})

sensors = {"living room": 21, "kitchen": 23, "bedroom": 20}
sensors.update({"pantry": 22, "guest room": 25, "patio": 34})

# 이미 존재하는 key 값의 value를 바꾸는 것도 가능하다. (이러면 팬트리의 값은 30으로 바뀜.)
sensors['pantry'] = 30

# 리스트 2개를 합쳐서 딕셔너리로 만들 수 있다. (zip() )
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
heights = [61, 70, 67, 64]
students = {key:value for key, value in zip(names, heights)}
# students is now {'Jenny': 61, 'Alexus': 70, 'Sam': 67, 'Grace': 64}
  • {} 사용한다.
  • {key:value} 사이 사이는 콤마로 구분한다.
  • value는 어떤 type이던지 상관 없다. (string,number, list, another dictionary) 그러나 key 는 숫자나 string만 가능하다. (튜플은 가능)
    key가 변하는 값인지 변하지 않는 값인지에 달려있다. 예를 들어서, 리스트는 값들이 변화 할 수 있기때문에 key로 쓸 수 없다.

딕셔너리 관련 함수,메서드

get and delete Key

building_heights = {"Burj Khalifa": 828, "Shanghai Tower": 632, "Abraj Al Bait": 601, "Ping An": 599, "Lotte World Tower": 554.5, "One World Trade": 541.3}

# key의 value 구하기 (원하는 key의 value를 return 한다)
building_heights["Burj Khalifa"] #828


# try/except 사용해서 해당 key가 딕셔너리 안에 있는지 알아내기 (Key인 Landmark 81이 딕셔너리 building_heights에 있는지 없는지 확인하는 법 )
key_to_check = "Landmark 81"
try:
  print(building_heights[key_to_check])
except KeyError:
  print("That key doesn't exist!")

'''
try:
	print(딕셔너리[찾고싶은 key])
except KeyError: # keyerror가 뜬다면
	print("출력할 문자")
'''

# in 사용해서 해당 key가 딕셔너리 안에 있는지 알아내기
# 결과 값은 불타입으로 True,False 로만 나타남.
"Shanghai Tower" in building_heights   # True


# .get() 사용해서 key의 value 얻기
# 딕셔너리.get('찾고싶은 key', default value) | default value-> key가 존재하지 않을시 리턴할 값
building_heights.get('Shanghai Tower', 0) # 상하이 타워가 있으니깐 632 리턴해줌.
building_heights.get('Mt Olympus', 0) # mt 올림푸스가 없으니깐 0을 리턴해준다.


# .pop() 사용해서 key 삭제
# 딕셔너리.pop("삭제할 key", default value) | default value-> key가 존재하지 않을시 리턴할 값
# key:value 를 쌍으로 삭제한 뒤, 삭제한 값을 반환한다. 
building_heights.pop("Burj Khalifa", "don't exist")

# del 사용해서 요소 삭제 하기
# del 딕셔너리[key]
del building_heights["Burj Khalifa"]


# Key 리스트 만들기
# 딕셔너리.keys()    ==> `dic_keys`  객체를 돌려준다(파이썬 3.0 이후)
building_heights.keys()   # building_heights의 key들만 모아서 `dic_keys` 객체를 돌려준다.

# key를 리스트로 반환 (`dic_keys`  객체가 아닌 리스트로 반환)
# list(딕셔너리.keys())
list(building_heights.keys())

# value 리스트 만들기
# 딕셔너리.values()
building_heights.values()

# key, value 쌍으로 얻기
# 딕셔너리.items()
building_heights.items()

딕셔너리에서 key는 고유한 값이기 때문에, 중복되는 key값을 설정해 놓으면 하나를 제외한 나머지 것들이 모두 무시된다.

pop()과 del 의 차이

tarot = { 1:	"The Magician", 2:	"The High Priestess", 3:	"The Empress", 4:	"The Emperor", 5:	"The Hierophant", 6:	"The Lovers", 7:	"The Chariot", 8:	"Strength", 9:	"The Hermit", 10:	"Wheel of Fortune", 11:	"Justice", 12:	"The Hanged Man", 13:	"Death", 14:	"Temperance", 15:	"The Devil", 16:	"The Tower", 17:	"The Star", 18:	"The Moon", 19:	"The Sun", 20:	"Judgement", 21:	"The World", 22: "The Fool"}

spread = {}
# print(tarot.pop(13))
# print(del tarot[1])

# spread["past"] = del tarot[13]
spread["past"] = tarot.pop(13)
spread["present"] = tarot.pop(22)
spread["future"] = tarot.pop(10)

for key,value in spread.items():
  print(f"Your {key} is the {value} card.")

위 코드는 삭제한 key를을 spread의 빈 딕셔너리에 넣어야 하는 코드이다. 근데 이상하게 pop은 되고, del은 안됐다.
그 이유는...!

pop()을 사용하면, return 값이 존재한다. 즉, return값은 pop()을 사용해서 삭제 한 값이 된다.

그러나 del은 {key:value} 자체를 삭제하고, return 값을 가지고 있지 않는다.




갑자기 조금 헷갈렸던것... (return)

i = 0
i+=3
print(i)
# 실행됨. 
----------
i = 0
print(i+=3)
# 실행 안됨.
--------------
def add (a,b):
    return a+=b

add(1,3) 
# 실행 안됨

이유는??
++,+=,-= 같은것들은 처리해야 하는 하는 애들임.
근데 print() 안에는 값만 들어 갈 수 있다.
값만 return 할 수 있는데 자꾸 처리해야하는 것들을 넣으니깐 실행이 안된다.

python 3.0 이상에서의 dict_keys,values,items

dict_keys 객체는 리스트를 사용하는 것과 차이가 없지만, 리스트 고유의 append,insert,pop,remove,sort 는 수행 할 수 없다.

.keys(), .values(), items() 로 반환하면 객체임.

test_scores = {"Grace": [80, 72, 90], "Jeffrey": [88, 68, 81], "Sylvia": [80, 82, 84], "Pedro": [98, 96, 95], "Martin": [78, 80, 78], "Dina": [64, 60, 75]}

a = test_scores.keys()  # test_scores들의 key들만 모아서 dict_keys 객체를 돌려준다.
a.pop()  # dict_keys 객체는 pop 사용 불가능

print(type(a)) # <class 'dict_keys'>
print(a)     # dict_keys(['Grace', 'Jeffrey', 'Sylvia', 'Pedro', 'Martin', 'Dina'])

딕셔너리를 리스트로 바꾸기

# 키를 리스트로 변환
dict = {'b': 4, 1: 8, 'a': 2}
lst = list(dict)
print( lst )   #['b', 1, 'a']

# value를 리스트로 변환
dict = {'b': 4, 1: 8, 'a': 2}
lst = list(dict.values())
print( lst )    # [4, 8, 2]

# 리스트 안에 튜플로..
dict = {'b': 4, 1: 8, 'a': 2}
print( list(zip(dict.keys(),dict.values())) )   # [('b', 4), (1, 8), ('a', 2)]

0개의 댓글