Python

dictionary

11mia 2020. 9. 9. 01:01

# dictionary type = { key1:value1, key2:value2 }

kim = {'age': 26, 'sex': 'M', 'height': 180}
print(kim)

lee = {'age': 25, 'sex': 'F', 'height': 160, 'height': 165}
print(lee) #key가 중복되는 경우: 가장 뒤에 있는 값만 사용

====Result====
{'age': 26, 'sex': 'M', 'height': 180}
{'age': 25, 'sex': 'F', 'height': 165}
dic = {'one': 1, 0: False, 3.5: [3, 4], 4: (3, 4), 'r': range(3)}
print(dic)

dict1 = {'dic1': 1, 'dic2': {'dic3': 3}}
print(dict1)

dict2 = {(3, 4): 3}
print(dict2)

dict3 = {range(3): 'r'}
print(dict3)

'''
#TypeError: unhashable type: 'list'
dict4 = {[3, 4]: 3}
print(dict4)

#TypeError: unhashable type: 'dict'
dict4 = {{1: True}: 'ok'}
print(dict4)
'''

====Result====
{'one': 1, 0: False, 3.5: [3, 4], 4: (3, 4), 'r': range(0, 3)}
{'dic1': 1, 'dic2': {'dic3': 3}}
{(3, 4): 3}
{range(0, 3): 'r'}

 

# empty dictionary

  • dictionary = {}
  • dictionary = dict()
dict1 = {}
dict2 = dict()

print(dict1)
print(dict2)

====Result====
{}
{}

 

# dict을 이용한 dictionary 생성

  • dictionary = dict(key1=value1, key2=value2)
  • dictionary = dict(zip([key1, key2], [value1, value2]))
  • dictionary = dict([(key1, value1), (key2, value2)])
  • dictionary = dict({key1: value1, key2: value2})
#1. dict(key1=value1, key2=value2)
kim = dict(age=26, sex='M', height=180)
print(kim) #key에는 따옴표를 사용하지 않아야함
'''
# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
kim = dict('age'=26, 'sex'='M', 'height'=180)
'''

====Result====
{'age': 26, 'sex': 'M', 'height': 180}
#2. dict(zip([key1, key2], [value1, value2]))
kim = dict(zip(['age', 'sex', 'height'], [26, 'M', 180]))
print(kim)

====Result====
{'age': 26, 'sex': 'M', 'height': 180}
#3. dict([(key1, value1), (key2, value2)])
kim = dict([('age', 26),('sex', 'M'), ('height', 180)])
print(kim)

====Result====
{'age': 26, 'sex': 'M', 'height': 180}
#4. dict({key1: value1, key2: value2})
kim = dict({'age': 26, 'sex': 'M', 'height': 180})
print(kim)

====Result=====
{'age': 26, 'sex': 'M', 'height': 180}

 

# 활용

kim = dict({'age': 26, 'sex': 'M', 'height': 180})
print('특정 key 접근')
print(kim['age'])
# print(kim[]) # SyntaxError: invalid syntax#
print(kim)
# print(kim['hair']) # KeyError: 'hair'

print('\n값 할당')
kim['sex']='F'
kim['nation'] = 'korea'
print(kim)

print('\nkey 존재 여부 확인')
print('hair' in kim)
print('hair' not in kim)

print('\nkey의 갯수 확인')
print(len(kim))

====Result====
특정 key 접근
26
{'age': 26, 'sex': 'M', 'height': 180}

값 할당
{'age': 26, 'sex': 'F', 'height': 180, 'nation': 'korea'}

key 존재 여부 확인
False
True

key의 갯수 확인
4