- dictionary 특징
- 시퀀스 자료형
- Key-Value 구조의 사전형 자료형
dict = {
True : 1,
False : 2,
"key1" : {
"child_key1" : "child_value1",
"child_key2" : "child_value2",
},
"key2" : "value2",
}
dict.get(key) # key 값 체크
if dict.get(key):
# key값이 존재할경우
else:
# 빈값일 경우
dict.keys()
# dict_keys([True, False, 'key1', 'key2'])
dict.values()
# dict_values([1, 2, {'child_key1': 'child_value1', 'child_key2': 'child_value2'}, 'value2'])
dict.items()
# dict_items([(True, 1), (False, 2), ('key1', {'child_key1': 'child_value1', 'child_key2': 'child_value2'}), ('key2', 'value2')])
del(dict[key])
dic1 = {1:10, 2:20}
dic2 = {1:100, 3:300}
dic1.update(dic2)
{1: 100, 2: 20, 3: 300}
- 정렬
- 역순, value, 다차원 정렬 등은 lambda식 활용을 통해 할 수 있습니다.
graph = {'txt': 3, 'spc': 2, 'icpc': 2, 'world': 1}
sorted_graph = sorted(graph.items())
print(sorted_graph)
# - 역순 정렬
sorted_graph = sorted(graph.items(), key= lambda x: (-x[1], x[0]))
[('icpc', 2), ('spc', 2), ('txt', 3), ('world', 1)]
arr = [6, 5, 6, 4, 4, 1, 1, 2, 3, 9, 8, 7, 9, 8, 7]
# 리스트 값들을 key로 변경
result1 = dict.fromkeys(arr)
print(result1)
# {6: None, 5: None, 4: None, 1: None, 2: None, 3: None, 9: None, 8: None, 7: None}
result2 = list(result1)
print(result2)
# [6, 5, 4, 1, 2, 3, 9, 8, 7]
# 좌표 압축
dic = {arr[i] : i for i in range(arr)}