Python : Dictionary

김가영·2020년 10월 4일
post-thumbnail

Dictionary?


  • key 와 value 의 쌍으로 이루어진 데이터 형태
  • key는 어떤 type이든 가능하지만 반드시 유일.

Dictionary 만드는 법


빈 딕셔너리

pringles_dic = {}
pringles_dic = dict()

딕셔너리

pringles_dic = {'green' : 'sourcream',
		'green' : 'onion', # overwrite 됨
            	'yellow' : 'cheeze'}
                
pringles_dic = dict(purple = "mayo" , red = "pepper")
  • list to dictionary
prices = dict([['item_a',100],['item_b',200],['item_c',300]])
prices = dict([('item_a',100),('item_b',200),('item_c',300)])
  • tuple to dictionary
prices = dict((('item_a',100),('item_b',200),('item_c',300)))
  • zip to dictionary
member_dict = dict(zip(['name','birth_year','birth_month'],['김가영','1997','9']))

추가 / 변경


이미 존재하는 key 면 변경 / 아니면 추가

member_dict['birth_year'] = 2020

.update() : 결합(병합)


prices2 = dict([('item_d',100),('item_e',200)])
prices.update(prices2)

기타함수


del

del prices['item_e'] 

in

print('item_a' in prices) # True

clear()

prices.clear()
print(prices) # {}

get()

prices['item_e'] : key 가 없으면 error
error 없이 가져올 수 있는 방법이 .get()

print(prices.get('item_g')) # None
print(prices.get('item_g',0)) # default value - 없으면 0 출력

모든 키 / value 얻기

print(prices.keys())
print(prices.values())
print(prices.items())


sorted

key 로 정렬

print(sorted(prices))

할당 복사

prices2 = prices.copy() # 복사
prices3 = prices # 할당
profile
개발블로그

0개의 댓글