Python, 딕셔너리 Dict()

moredev·2022년 11월 17일
0

python

목록 보기
2/4

딕셔너리

파이썬에서 key:value를 한 쌍으로 갖는 자료형
key에는 불변형 객체, value에는 가변형 객체를 사용한다.

기본 형태

# {Key1:Value1, Key2:Value2, Key3:Value3, ...}

# ex)
dictionaries = {
		'id': 20221109001,
        'title': 'data type built into Python',
        'create_time':'2022-11-09'
}

추가

딕셔너리 변수에 키와 값을 할당하여 값을 추가한다.

dictionaries['sub_title'] = 'dictionaries'
print(dictionaries)

결과

{'id': 20221109001, 'title': 'data type built into Python', 'create_time': '2022-11-09', 'sub_title': 'dictionaries'}

삭제

키값을 입력하여 특정 데이터를 삭제한다.

del dictionaries['sub_title']
print(dictionaries)

결과

{'id': 20221109001, 'title': 'data type built into Python', 'create_time': '2022-11-09'}

더하기

두 딕셔너리를 하나의 딕셔너리로 더한다.
딕셔너리에서 키 값은 중복될 수 없다. 두 딕셔너리를 더하는데, 같은 키 값이 존재한다면 뒤의 키 값만 남게 된다.

update()

dict1 = {'a': 0, 'b': 'BBB', 'c': 123}
dict2 = {'d': 'DDD', 'e': 'EEE'}
dict3 = {'e':'Dictionaries', 'f': 'FFF', 'g': 'GGG'}

dict1.update(dict2)
print(dict1)

dict1.update(dict3)
print(dict1)

결과

{'a': 0, 'b': 'BBB', 'c': 123, 'd': 'DDD', 'e': 'EEE'}
{'a': 0, 'b': 'BBB', 'c': 123, 'd': 'DDD', 'e': 'Dictionaries', 'f': 'FFF', 'g': 'GGG'}

찾기

key

  • keys() 함수를 이용해 딕셔너리의 키를 볼 수 있다. for .. in을 사용해 키 값을 하나씩 사용할 수 있다.
dict = {'a': 0, 'b': 'BBB', 'c': 123, 'd': 'DDD', 'e': 'Dictionaries', 'f': 'FFF', 'g': 'GGG'}

print(dict.keys())

for i in dict.keys():
    print(f'key : {i}')

결과

dict_keys(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
key : a
key : b
key : c
key : d
key : e
key : f
key : g
  • if .. in을 사용하면 키가 해당 딕셔너리에 있는지 확인할 수 있다.
dict = {'a': 0, 'b': 'BBB', 'c': 123, 'd': 'DDD', 'e': 'Dictionaries', 'f': 'FFF', 'g': 'GGG'}

if 'a' in dict:
    print('True')
else:
    print('False')
    
if 1 in dict:
    print('True')
else:
    print('False')

결과

True
False
  • list() 함수를 사용해 키 값들을 리스트로 반환할 수 있다.
list = list(dict.keys())
print(list)

결과

['a', 'b', 'c', 'd', 'e', 'f', 'g']

value

  • key를 이용해 특정 값을 찾는다. vlaues() 함수를 이용해 값들을 한번에 볼 수 있다.
dict = {'a': 0, 'b': 'BBB', 'c': 123, 'd': 'DDD', 'e': 'Dictionaries', 'f': [1, 2, 3], 'g': 'GGG'}

print(dict['a'])
print(dict['e'])
print(dict['f'])
print(dict.values())

결과

0
Dictionaries
[1, 2, 3]
dict_values([0, 'BBB', 123, 'DDD', 'Dictionaries', [1, 2, 3], 'GGG'])

key, value

  • items() 함수를 이용해 키와 값을 모두 볼 수 있다.
dict = {'a': 0, 'b': 'BBB', 'c': 123, 'd': 'DDD', 'e': 'Dictionaries', 'f': 'FFF', 'g': 'GGG'}

print(dict.items())

for i in dict.items():
    print(i)

결과

dict_items([('a', 0), ('b', 'BBB'), ('c', 123), ('d', 'DDD'), ('e', 'Dictionaries'), ('f', 'FFF'), ('g', 'GGG')])
('a', 0)
('b', 'BBB')
('c', 123)
('d', 'DDD')
('e', 'Dictionaries')
('f', 'FFF')
('g', 'GGG')

지우기

  • clear 함수를 사용해 딕셔너리 안의 모든 요소를 삭제한다. 빈 딕셔너리는 {}로 표현한다.
dict.clear()
print(dict)

결과

{}

0개의 댓글