RL Researcher

13. Dictionary(딕셔너리) 본문

AI Basic/Python Programming

13. Dictionary(딕셔너리)

Lass_os 2021. 1. 3. 18:29

1. Dictionary(딕셔너리)


  • 딕셔너리 타입은 immutable한 키(key)와 mutable한 값(value)으로 맵핑되어 있는 순서가 없는 집합입니다.

  • 중괄호로 되어 있고 키와 값이 있습니다.

print({"a" : 1, "b":2})

========================================================================

<output>
{'a': 1, 'b': 2}
  • 키로는 immutable한 값은 사용할 수 있지만, mutable한 객체는 사용할 수 없습니다.

# immutable 예
a = {1: 5, 2: 3}   # int 사용
print(a)

a = {(1,5): 5, (3,3): 3} # tuple사용
print(a)

a = { 3.6: 5, "abc": 3} # float 사용
print(a)

a = { True: 5, "abc": 3} # bool 사용
print(a)

========================================================================

<output>
{1: 5, 2: 3}
{(1, 5): 5, (3, 3): 3}
{3.6: 5, 'abc': 3}
{True: 5, 'abc': 3}
# mutable 예
print(a = { {1, 3}: 5, {3,5}: 3})     #set 사용 에러

========================================================================

<output>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'


print(a = {[1,3]: 5, [3,5]: 3})     #list 사용 에러

========================================================================

<output>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


print(a = { {"a":1}: 5, "abc": 3})     #dict 사용 에러

========================================================================

<output>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
  • 값은 중복될 수 있지만, 키가 중복되면 마지막 값으로 덮어씌워집니다.

print({"a" : 1, "a":2})

========================================================================

<output>
{'a': 2}
  • 순서가 없기 때문에 인덱스로는 접근할수 없고, 키로 접근 할 수 있습니다.

d = {'abc' : 1, 'def' : 2}
print(d[0])

========================================================================

<output>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0


print(d['abc'])

========================================================================

<output>
1
  • mutable 한 객체이므로 키로 접근하여 값을 변경할 수 있습니다.

d['abc'] = 5
print(d)

========================================================================

<output>
{'abc': 5, 'def': 2}
  • 새로운 키와 값을 아래와 같이 추가할 수 있습니다.

d['ghi'] = 999
print(d)

========================================================================

<output>
{'abc': 5, 'def': 2, 'ghi': 999}

2. dictionary(딕셔너리) 선언


  • 딕셔너리 선언할때는 빈 중괄호를 사용합니다.(set 중괄호를 이용하지만 빈중괄호로 선언하면 type이 dict가 됩니다.)

  • 딕셔너리로 명시적으로 선언할 수도 있습니다.

e = {}
print(type(e))

f = dict()
print(type(f))

========================================================================

<output>
<class 'dict'>
<class 'dict'>
  • dict constructor를 통해서 아래와 같이 바로 키와 값을 할당하며 선언할 수 있습니다.

newdict = dict( alice = 5, bob = 20, tony= 15, suzy = 30)
print(newdict)

========================================================================

<output>
{'alice': 5, 'bob': 20, 'tony': 15, 'suzy': 30}

 

3. dictionary(딕셔너리) 변환


  • 리스트 속에 리스트나 튜플, 튜플속에 리스트나 튜플의 값을 키와 value를 나란히 입력하면, 아래와 같이 dict로 변형할 수 있습니다.

name_and_ages = [['alice', 5], ['Bob', 13]]
print(dict(name_and_ages))

name_and_ages = [('alice', 5), ('Bob', 13)]
print(dict(name_and_ages))

name_and_ages = (('alice', 5), ('Bob', 13))
print(dict(name_and_ages))

name_and_ages = (['alice', 5], ['Bob', 13])
print(dict(name_and_ages))

========================================================================

<output>
{'alice': 5, 'Bob': 13}
{'alice': 5, 'Bob': 13}
{'alice': 5, 'Bob': 13}
{'alice': 5, 'Bob': 13}

4. dictionary update(딕셔너리 수)


  • 단일 수정은 키로 접근하여 값을 할당하면 됩니다.

a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30}
a['alice'] = 5
print(a)

========================================================================

<output>
{'alice': 5, 'bob': 20, 'tony': 15, 'suzy': 30}

 

  • 여러값 수정은 update 메소드를 사용합니다. 키가 없는 값이면 추가됩니다.

a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30}
a.update({'bob':99, 'tony':99, 'kim': 30})
print(a)

========================================================================

<output>
{'alice': [1, 2, 3], 'bob': 99, 'tony': 99, 'suzy': 30, 'kim': 30}

5. dictionary(딕셔너리) for문


  • for문을 통해 딕셔너리를 for문을 돌리면 key값이 할당됩니다.

  • 순서는 임의적이다.같은 순서를 보장할 수 없다.

a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30}
for key in a:
	print(key)

========================================================================

<output>
alice
bob
tony
suzy
  • value값으로 for문을 반복하기 위해서는 values() 를 사용해야합니다.

for val in a.values():
	print(val)

========================================================================

<output>
[1, 2, 3]
20
15
30    
  • key와 value를 한꺼번에 for문을 반복하려면 items() 를 사용합니다.

for key, val in a.items():
	print("key = {key}, value={value}".format(key=key,value=val))

========================================================================

<output>
key = alice, value=[1, 2, 3]
key = bob, value=20
key = tony, value=15
key = suzy, value=30

6. dictionary(딕셔너리)의 in


  • dictionary의 in은 키에 한해서 동작합니다.
print('alice' in a)
print('teacher' in a)
print('teacher' not in a)

========================================================================

<output>
True
False
True

7. dictionary(딕셔너리)의 요소 삭제


  • list와 마찬가지로 del키워드를 사용합니다.

a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30}
del a['alice']
print(a)

========================================================================

<output>
{'bob': 20, 'tony': 15, 'suzy': 30}

 

'AI Basic > Python Programming' 카테고리의 다른 글

05. for in 반복문, Range, enumerate  (0) 2021.01.04
14. Set(집합)  (0) 2021.01.03
12. 튜플(tuple)  (0) 2021.01.03
15. 함수(function)  (0) 2020.12.27
11. 리스트(List) - 5 - 리스트 정렬  (0) 2020.12.25
Comments