[딕셔너리 기본적 사용법 ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # 딕셔너리 dic = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} # Key : Value 형태 ############################### # 딕셔너리 추가하기 a = {1: 'a'} a[2] = 'b' a['name'] = 'pey' a[3] = [1,2,3] print(a) # 결과 # {1: 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]} ############################### # 딕셔너리 요소 삭제 del a[1] print(a) # 결과 # {2: 'b', 'name': 'pey', 3: [1, 2, 3]} ############################### # 딕셔너리 Value 얻기 grade = {'pey': 10, 'julliet': 99} print(grade['pey']) print(grade['julliet']) # 결과 # 10 # 99 | cs |
[딕셔너리 관련 함수 ]
함수 | 설명 |
keys | Key만을 모아서 dict_keys라는 객체를 리턴 |
values | Value만을 모아서 dict_values 객체가 리턴 |
items | key와 value의 쌍을 튜플로 묶은 값을 dict_items 객체로 리턴 |
clear | clear() 함수는 딕셔너리 안의 모든 요소를 삭제, 빈 딕셔너리 { }반환 |
get | get(x) 함수는 x라는 key에 대응되는 value를 돌려준다. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | # Key 리스트 만들기(keys) a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'} print(a.keys()) print(list(a.keys())) # dict_keys 객체를 list로 변환 후 사용 # 결과 # dict_keys(['name', 'phone', 'birth']) # ['name', 'phone', 'birth'] ############################################ # Value 리스트 만들기(values) print(a.values()) # 결과 # dict_values(['pey', '0119993323', '1118']) ############################################ # Key, Value 쌍 얻기(items) print(a.items()) # 결과 # dict_items([('name', 'pey'), ('phone', '0119993323'), ('birth', '1118')]) ############################################ # Key: Value 쌍 모두 지우기(clear) a.clear() print(a) # 결과 # {} ############################################ # Key로 Value얻기(get) a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} print(a.get('name')) print(a.get('phone')) print(a.get('foo', 'bar')) # 찾으려는 key 값이 없을 경우 default 값 지정 가능 # 결과 # 'pey' # '0119993323' # 'bar' ############################################ # 해당 Key가 딕셔너리 안에 있는지 조사하기(in) a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} print('name' in a) print('email' in a) # 결과 # True # False | cs |
출처- wikidocs 점프 투 파이썬 (박응용)
'IT,인터넷 관련 학습 > Python 학습' 카테고리의 다른 글
파이썬(Python) 기초 : 변수 (0) | 2019.05.05 |
---|---|
파이썬(Python) 기초 : 불(bool), 논리(logical) 자료형 (0) | 2019.05.05 |
파이썬(Python) 기초 : 리스트(list), 튜플(tuple) (0) | 2019.05.04 |
파이썬(Python) 기초 : 숫자형, 문자열 (0) | 2019.05.04 |
파이썬(Python) 기초 : 집합(set) (0) | 2019.02.25 |