#21-파이썬 기초 실습 - 딕셔너리 Dictonary - 2

2020. 2. 1. 07:57AI & BigData/Python Basics

파이썬 기초 실습 - 딕셔너리 Dictionary - 2

4. 딕셔너리의 해시 기법

In [1]:

dict_d = {'one':1,'two':2,'three':3,'four':4}
del dict_d['one']  # 키가 'one'인 것을 삭제한다.
dict_d

Out[1]:

{'two': 2, 'three': 3, 'four': 4}

In [2]:

dict_d['one'] = 1  # 삭제된 값을 다시 입력
dict_d

Out[2]:

{'two': 2, 'three': 3, 'four': 4, 'one': 1}

In [3]:

dict_d[(1,2,3)] = 'tuple'  # 튜플 자체를 키로 넣는 것이 가능한지 시도.
dict_d

Out[3]:

{'two': 2, 'three': 3, 'four': 4, 'one': 1, (1, 2, 3): 'tuple'}

In [4]:

dict_d[[1,2,3]] = 'list'  # 리스트 자체를 키로 넣는 것이 가능한지 시도. 리스트는 해쉬화가 불가능하여 에러.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-a9348a1b1059> in <module>
----> 1 dict_d[[1,2,3]] = 'list'  # 리스트 자체를 키로 넣는 것이 가능한지 시도. 리스트는 해쉬화가 불가능하여 에러.

TypeError: unhashable type: 'list'

In [5]:

dict_d[{'two': 2}] = 'dict'  # 사전 타입도 해쉬화가 불가능하여 에러. TypeError: unhashable type: 'dict'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-badfffe5c147> in <module>
----> 1 dict_d[{'two': 2}] = 'dict'  # 사전 타입도 해쉬화가 불가능하여 에러. TypeError: unhashable type: 'dict'

TypeError: unhashable type: 'dict'

1. 딕셔너리의 주요 내장 메서드

  • keys(). 사전에 들어있는 키를 추출하여 보여준다.

In [6]:

# 키 딕셔너리 확인
dict_d = {'one':1,'two':2,'three':3,'four':4}
dict_d.keys()

Out[6]:

dict_keys(['one', 'two', 'three', 'four'])

In [7]:

dict_e = dict_d.keys()  # b가 리스트인지 확인한다.
dict_e

Out[7]:

dict_keys(['one', 'two', 'three', 'four'])

In [8]:

type(dict_e) # dict_keys'라는 타입이다.

Out[8]:

dict_keys

In [9]:

# b는 리스트가 아니라서 인섹싱을 지원하지 않고.. 에러를 반환한다.
dict_e[1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-0ba856c4dd60> in <module>
      1 # b는 리스트가 아니라서 인섹싱을 지원하지 않고.. 에러를 반환한다.
----> 2 dict_e[1]

TypeError: 'dict_keys' object is not subscriptable

In [10]:

# values(). 사전에 들어있는 값만을 추출하여 보여준다.
dict_d = {'one':1,'two':2,'three':3,'four':4}
dict_d.values()

Out[10]:

dict_values([1, 2, 3, 4])

In [11]:

dict_e = dict_d.values()  # b가 리스트인지 확인한다.
type(dict_e)

Out[11]:

dict_values

In [12]:

# items(). 사전에 어떤 데이터가 있는지 키와 값을 묶어서 보여준다.
dict_d = {'one':1,'two':2,'three':3,'four':4}
dict_d.items() 

Out[12]:

dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4)])

In [13]:

dict_e = dict_d.items()  # 무슨 타입인지 확인하기 위한 처리.
type(dict_e)  

Out[13]:

dict_items

In [14]:

# .get(a, default). a라는 키를 넣으면 a의 값을 출력한다. 만약 a라는 키가 없으면 default를 출력한다.
dict_d = {'one':1,'two':2,'three':3,'four':4}
print(dict_d.get('one'))
print(dict_d.get('to'))
print(dict_d.get('fou','no key'))
1
None
no key

In [15]:

# copy()를 이용하면 내용만 복사하여 a가 바뀌어도 b에는 변화가 없다.
dict_d = {'one': 10, 'two': 20, 'three': 30, 'four': 40}
dict_e = dict_d  # b에 a의 주소값을 할당한다.
print(dict_d == dict_e)  # 주소값이 동일하므로 내용도 같다. 결과는 True.
print(dict_d is dict_e)  # 주소값이 동일하므로 결과는 True.
True
True

In [16]:

dict_d['five'] = 50         # five에 새로운 값 추가
print(dict_d == dict_e)          # 주소값이 동일하므로 내용도 같다. 결과는 True.
print(dict_d is dict_e)          # 주소값이 동일하므로 결과는 True.
print(id(dict_d) == id(dict_e))  # id가 동일한 것을 확인. True
True
True
True

In [17]:

print(dict_d)
print(dict_e)
{'one': 10, 'two': 20, 'three': 30, 'four': 40, 'five': 50}
{'one': 10, 'two': 20, 'three': 30, 'four': 40, 'five': 50}

In [18]:

dict_f = dict_d.copy  # .copy()를 사용하여 c 객체 생성

In [19]:

print(dict_d)
print(dict_e)
print(dict_f)
{'one': 10, 'two': 20, 'three': 30, 'four': 40, 'five': 50}
{'one': 10, 'two': 20, 'three': 30, 'four': 40, 'five': 50}
<built-in method copy of dict object at 0x0000021826F1E818>

In [20]:

dict_d == dict_f 

Out[20]:

False

In [21]:

dict_d is dict_f

Out[21]:

False

In [22]:

id(dict_d) == id(dict_f)

Out[22]:

False

In [23]:

print(type(dict_d))
print(type(dict_e))
print(type(dict_f))
<class 'dict'>
<class 'dict'>
<class 'builtin_function_or_method'>

In [24]:

dict_f = dict_d

In [25]:

print(type(dict_f))
<class 'dict'>

In [26]:

# popitem() 가장 뒷쪽에 데이터를 하나씩 빼고 기존 값은 삭제 됨
# 출력하고 반환한다.

In [27]:

dict_d={'one':1,'two':2,'three':3,'four':4} 
dict_d.popitem() 

Out[27]:

('four', 4)

In [28]:

dict_d.popitem() 

Out[28]:

('three', 3)

In [29]:

dict_d.popitem() 

Out[29]:

('two', 2)

In [30]:

dict_d.popitem()

Out[30]:

('one', 1)

In [31]:

dict_d  # {}

Out[31]:

{}

In [32]:

# pop(key) popitem()과 동일한 효과를 가지고 있다. 
# popitem()과 다른 점은 키를 입력하여 원하는 값을 나오게 할 수 있다는 점
dict_d = {'one':1,'two':2,'three':3,'four':4}
dict_d.pop('one')

Out[32]:

1

In [33]:

dict_d

Out[33]:

{'two': 2, 'three': 3, 'four': 4}

In [34]:

# update(). 사전 타입에 사전 타입을 요소로 집어넣을 때 사용하는
dict_d={'one':1,'two':2,'three':3,'four':4}
dict_e={'five':5}
dict_d.update(dict_e)  
dict_d

Out[34]:

{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

In [35]:

# clear(). 딕셔너리 내용을 전체 삭제
dict_d = {'one':1,'two':2,'three':3,'four':4}
dict_d.clear() 
dict_d  

Out[35]:

{}

In [ ]: