본문 바로가기
Python

딕셔너리

by 자동매매 2025. 9. 4.

딕셔너리 

  • 딕셔너리 = {키1: 값1, 키2: 값2}

 

>>> lux = {'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}
>>> lux
{'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}

 

※ 딕셔너리의 키는 문자열뿐만 아니라 정수, 실수, 불도 사용할 수 있으며 자료형을 섞어서 사용해도 됩니다. 그리고 값에는 리스트, 딕셔너리 등을 포함하여 모든 자료형을 사용할 수 있습니다. 단, 키에는 리스트와 딕셔너리를 사용할 수 없습니다.

>>> x = {100: 'hundred', False: 0, 3.5: [3.5, 3.5]}
>>> x
{100: 'hundred', False: 0, 3.5: [3.5, 3.5]}

 

빈 딕셔너리 만들기

빈 딕셔너리를 만들 때는 { }만 지정하거나 dict를 사용하면 됩니다. 보통은 { }를 주로 사용합니다.

  • 딕셔너리 = {}
  • 딕셔너리 = dict()
>>> x = {}
>>> x
{}
>>> y = dict()
>>> y
{}

 

 

dict로 딕셔너리 만들기

  • 딕셔너리 = dict(키1=값1, 키2=값2)
  • 딕셔너리 = dict([(키1, 값1), (키2, 값2)])
  • 딕셔너리 = dict(((키1, 값1), (키2, 값2)))

  • 딕셔너리 = dict(zip([키1, 키2], [값1, 값2]))

  • 딕셔너리 = dict({키1: 값1, 키2: 값2})

 

딕셔너리의 키에 접근

  • 딕셔너리[키]
>>> lux = {'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}
>>> lux['health']
490
>>> lux['armor']
18.72

 

 

딕셔너리의 키에 값 할당하기

  • 딕셔너리[키] = 값
>>> lux = {'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}
>>> lux['health'] = 2037    # 키 'health'의 값을 2037로 변경
>>> lux['mana'] = 1184      # 키 'mana'의 값을 1184로 변경
>>> lux
{'health': 2037, 'mana': 1184, 'melee': 550, 'armor': 18.72}

 

그럼 없는 키에서 값을 가져오려고 하면 어떻게 될까요?

딕셔너리는 없는 키에서 값을 가져오려고 하면 에러가 발생합니다.

>>> lux = {'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}
>>> lux['attack_speed']    # lux에는 'attack_speed' 키가 없음
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    lux['attack_speed']
KeyError: 'attack_speed'

 

 

딕셔너리에 키가 있는지 확인하기

  • 키 in 딕셔너리
>>> lux = {'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}
>>> 'health' in lux
True
>>> 'attack_speed' in lux
False
  • 키 not in 딕셔너리
>>> 'attack_speed' not in lux
True
>>> 'health' not in lux
False

이렇게 not in은 특정 키가 없으면 True, 있으면 False가 나옵니다.

 

딕셔너리의 키 개수 구하기

  • len(딕셔너리)
>>> lux = {'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72}
>>> len(lux)
4
>>> len({'health': 490, 'mana': 334, 'melee': 550, 'armor': 18.72})
4
 

zip() 기본 문법

zip() 함수는 여러 개의 순회 가능한(iterable) 객체를 인자로 받고, 각 객체가 담고 있는 원소를 튜플의 형태로 차례로 접근할 수 있는 반복자(iterator)를 반환합니다.

>>> numbers = [1, 2, 3]
>>> letters = ["A", "B", "C"]
>>> for pair in zip(numbers, letters):
...     print(pair)
...
(1, 'A')
(2, 'B')
(3, 'C')

 

입력 - 두줄 입력받기 결과
health health_regen mana mana_regen
575.6 1.7 338.8 1.63
{'health': 575.6, 'health_regen': 1.7, 'mana': 338.8, 'mana_regen': 1.63}
x = input().split()
y = map(float,input().split())
z=dict(zip(x,y))
print(z)

 

'Python' 카테고리의 다른 글

sequence자료형  (0) 2025.09.04
입력/출력  (1) 2025.08.31
변수  (1) 2025.08.31
숫자 체계  (0) 2025.08.31
내장함수  (1) 2025.08.30

댓글