dictionary[key] = v ⇒ key 라는 곳에 v 값 삽입 : O(1)
del dictionary[key] ⇒ key 라는 곳을 삭제 : O(1)
dictionary[key] ⇒ key 라는 곳에 있는 v 값 조회 : O(1)
ex = {1:'가', 2:'나', 3:'다'}
ex[4] = '라' # 삽입 O(1)
print(ex) >>> {1: '가', 2: '나', 3: '다', 4: '라'}
del ex[2] # 삭제 O(1) 주의! remove가 아닌 del을 사용해야 한다.
print(ex) >>> {1: '가', 3: '다', 4: '라'}
print(ex[3]) # 조회 O(1)
>>> 다
딕셔너리는 중복된 key값을 가질 수 없다. 중복된 key값을 쓰면 하나를 제외한 나머지는 무시된다.
a = {1:'a', 1:'b'}
print(a)
>>>{1: 'b'}
dic.get(key) : key값에 대응하는 value값을 출력한다. 이는 dic[key]와 같으나 만약 없는 key값을 출력하라고 하면 dic[key]는 error를 출력하고, dic.get(key)는 None을 출력함. 만약 해당 key가 없을 때 반환되는 값을 바꾸고 싶다면, get() 메소드의 두번째 인자로 주면 됨.
ex = {1:'가', 2:'나', 3:'다'}
print(ex.get(1))
>>> 가
print(ex[1])
>>> 가
print(ex[4])
>>> KeyError
print(ex.get(4))
>>> None
print(ex.get(4,0))
>>> 0
리스트나 튜플을 딕셔너리로 만들기
list1 = ['a','b','c','d','e']
list2 = [1,2,3,4,5]
li = []
for x,y in zip(list1, list2):
li.append((x,y))
print(li)
>>> [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
dic1 = dict(li)
print( dic1 ) # 리스트의 원소가 튜플이나 리스트로 길이가 2일 때 dict()를 하면 앞에 것은 key , 뒤에 것은 value가 된다.
>>> {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 좀 더 빠른 방법
dic2 = dict(zip(list2, list1))
print( dic2 )
>>> {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
딕셔너리에서 값을 확인 하는 방법에는 딕셔너리.keys(), 딕셔너리.items(), 딕셔너리.values()가 있다. 주의할 것은 ()를 안하면 객체가 생성되지 않는다. 또한 모두 s가 붙는 복수형이라는 것을 잊지 말자.
s = {'1':'a', '2':'b'}
s.keys()
>>> dict_keys(['1', '2'])
s.keys
>>> <function dict.keys>
s.values()
>>> dict_values(['a', 'b'])
s.values
>>> <function dict.values>
s.items()
>>> dict_items([('1', 'a'), ('2', 'b')])
s.items
>>> <function dict.items>
for 문 혹은 if 문에서 딕셔너리 이름을 쓰면 key값만 나오게 된다.
s = {'1':'a', '2':'b'}
for i in s:
print(i, end = ' ')
>>> 1 2
for i in s.keys():
print(i, end = ' ')
>>> 1 2
if '1' in s:
print(True)
>>> True
if '1' in s.keys():
print(True)
>>> True
만약 for문 혹은 if문에서 value값을 찾고 싶거나 item 값을 찾고 싶으면 .values() 혹은 .items()를 써야 한다.
ex) s = {'1':'a', '2':'b'}
for i in s.values():
print(i, end = ' ')
>>> a b
for i in s.items():
print(i, end = ' ')
>>> ('1', 'a') ('2', 'b')
if 'a' in s.values():
print(True)
>>> True
if ('1','a') in s.items():
print(True)
>>>> True
딕셔너리 정렬하기
dic = {'toy': 70, 'snack': 200, 'python': 10}
print(dic)
>>> {'toy': 70, 'snack': 200, 'python': 10}
1. 딕셔너리에 정렬을 하면 key값을 기준으로 key값을 정렬한 후 key값만 리스트로 출력함 이때, 주의할 점은 문자열을 정렬할때 정렬 순서는 문자열의 길이가 아닌 사전식 배열이 정렬의 기준임
print( sorted(dic) )
>>> ['python', 'snack', 'toy'] # 사전식 정렬
print( sorted(dic, reverse= True) )
>>> ['toy', 'snack', 'python'] # 사전식 배열의 내림차순으로 정렬
딕셔너리를 key값을 기준으로 정렬한 후 딕셔너리를 출력하는 방법
⇒ dic.items()를 정렬하면 key값을 기준으로 정렬됨. 이를 이용하면 key값을 기준으로 정렬된 딕셔너리를 출력할 수 있음
print( sorted(dic.items()) )
>>> [('python', 10), ('snack', 200), ('toy', 70)]
print( dict(sorted(dic.items())) )
>>> {'python': 10, 'snack': 200, 'toy': 70}
print( dict(sorted(dic.items(), reverse = True)) )
>>> {'toy': 70, 'snack': 200, 'python': 10} # key값을 기준으로 사전식 배열의 내림차순으로 정렬한 딕셔너리
3. 딕셔너리를 value값을 기준으로 정렬한 후 딕셔너리를 출력하는 방법
⇒ dic.items()를 정렬하면 value값을 기준으로 정렬됨. 이를 이용하면 value값을 기준으로 정렬된 딕셔너리를 출력할 수 있음
print( sorted(dic.items(), key = lambda x:x[1]) )
>>> [('python', 10), ('toy', 70), ('snack', 200)]
print( dict(sorted(dic.items(), key = lambda x:x[1])) )
>>> {'python': 10, 'toy': 70, 'snack': 200}
print( dict(sorted(dic.items(), key = lambda x:x[1], reverse = True)) )
>>> {'snack': 200, 'toy': 70, 'python': 10}
4. 딕셔너리를 key값의 문자열 길이를 기준으로 정렬하는 방법
print( sorted(dic, key = lambda x: len(x)) ) # 딕셔너리를 sort하면 key값을 기준으로 정렬됨. 이때 lambda를 써서 key값의 문자열 길이를 기준으로 정렬할 수 있음
>>> ['toy', 'snack', 'python']
print( sorted(dic, key = lambda x: len(x), reverse = True) )
>>> ['python', 'snack', 'toy']
print( sorted(dic.items(), key = lambda x: len(x[0])) )
>>> [('toy', 70), ('snack', 200), ('python', 10)]
print( sorted(dic.items(), key = lambda x: len(x[0]), reverse = True) )
>>> [('python', 10), ('snack', 200), ('toy', 70)]
print( dict(sorted(dic.items(), key = lambda x: len(x[0]))) ) # 딕셔너리의 key값의 문자열 길이를 기준으로 정렬한 딕셔너리
>>> {'toy': 70, 'snack': 200, 'python': 10}
print( dict(sorted(dic.items(), key = lambda x: len(x[0]), reverse = True)) )
>>> {'python': 10, 'snack': 200, 'toy': 70}