군침이 싹 도는 코딩
PYTHON DICTIONARIES - 데이터의 추가,수정,삭제 / 키값,벨류값,쌍으로 가져오기 (keys,values,items) 본문
Python/Basic
PYTHON DICTIONARIES - 데이터의 추가,수정,삭제 / 키값,벨류값,쌍으로 가져오기 (keys,values,items)
mugoori 2022. 11. 16. 17:10딕셔너리에 데이터 추가
my_phone
>>> {'brand': 'Apple', 'model': 'iPhone 12', 'year': 2018}
my_phone['color']= 'red'
my_phone
>>> {'brand': 'Apple', 'model': 'iPhone 12', 'year': 2018, 'color': 'red'}
# 딕셔너리에 데이터를 추가할때는 대괄호에 키값
# = 기호 오른쪽에 벨류값을 써주면 된다
딕셔너리에 데이터 수정
my_phone
>>> {'brand': 'Apple', 'model': 'iPhone X', 'year': 2018}
my_phone['model']= 'iPhone 12'
my_phone
>>> {'brand': 'Apple', 'model': 'iPhone 12', 'year': 2018}
# 딕셔너리의 벨류값을 바꾸고 싶으면 대괄호에 키값을 입력하고
# = 기호 오른쪽에 바꿀값을 입력하면 된다
딕셔너리에 데이터를 삭제하는 법
my_phone
>>> {'brand': 'Apple', 'model': 'iPhone 12', 'year': 2018}
del my_phone['model']
my_phone
>>> {'brand': 'Apple', 'year': 2018, 'color': 'red'}
# 딕셔너리 데이터 삭제는 파이썬의 기본기능 del 을 사용하며
# 대괄호에 키값만 넣으면 쌍으로 삭제가 된다
my_phone.clear()
my_phone
>>> {}
# 딕셔너리안에 모든 데이터를 삭제하고싶으면
# clear 함수를 사용한다
딕셔너리 안에 키값,벨류값,쌍으로 데이터를 가져오는법
my_phone
>>> {'brand': 'Apple', 'year': 2018, 'color': 'red'}
my_phone.keys()
>>> dict_keys(['brand', 'year', 'color'])
# 키값을 가져오고 싶다면 .keys() 함수를 이용
my_phone.values()
>>> dict_values(['Apple', 2018, 'red'])
# 벨류값을 가져오고 싶다면 .values() 함수를 이용
my_phone.items()
>>> dict_items([('brand', 'Apple'), ('year', 2021), ('color', 'red')])
# 둘다 가져오고 싶다면 .items() 함수를 이용
'Python > Basic' 카테고리의 다른 글
Python - Sets (add,discard) (0) | 2022.11.16 |
---|---|
Python - Tuples (0) | 2022.11.16 |
PYTHON DICTIONARIES - 생성/데이터 억세스(get) (0) | 2022.11.16 |
PYTHON LIST - 원하는값 찾기(인덱스)/연산/정렬(sorted,sort) (0) | 2022.11.16 |
PYTHON LIST - 추가/수정/삭제 하는법 (0) | 2022.11.15 |