딕셔너리

  • associative array (연관 배열)
  • { } 사용
  • key와 value로 이루어짐
d = {
    <key>: <value>,
    <key>: <value>,
      .
      .
      .
    <key>: <value>
}
  • 또는 dict()함수를 이용할 수 있다.
d = dict([
    (<key>, <value>),
    (<key>, <value),
      .
      .
      .
    (<key>, <value>)
])
  • Key가 단순 문자열일 경우 아래와 같이 사용 가능
>>> MLB_team = dict(
...     Colorado='Rockies',
...     Boston='Red Sox',
...     Minnesota='Twins',
...     Milwaukee='Brewers',
...     Seattle='Mariners'
... )

인덱스를 사용하지 않는다.

>>> MLB_team[1]
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    MLB_team[1]
KeyError: 1

>>> d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}

>>> d[0]
'a'
>>> d[2]
'c'

List 와 다른 점

1.인덱스 불가
2.슬라이스 불가
3. .append와 같은 매소드 불가

>>> type(d)
<class 'dict'>

>>> d[-1]
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    d[-1]
KeyError: -1

>>> d[0:2]
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    d[0:2]
TypeError: unhashable type: 'slice'

>>> d.append('e')
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    d.append('e')
AttributeError: 'dict' object has no attribute 'append'

Values 값 추출

>>> MLB_team['Minnesota']
'Twins'
>>> MLB_team['Colorado']
'Rockies'
  • Add a new key and value
>>> MLB_team['Kansas City'] = 'Royals'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners', 'Kansas City': 'Royals'}
  • Assign a new value to an existing key
>>> MLB_team['Seattle'] = 'Seahawks'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}
  • Delete an entry
>>> del MLB_team['Seattle']
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Kansas City': 'Royals'}

즉석으로 딕셔너리 만들기 a={}

>>> person = {}
>>> type(person)
<class 'dict'>

>>> person['fname'] = 'Joe'
>>> person['lname'] = 'Fonebone'
>>> person['age'] = 51
>>> person['spouse'] = 'Edna'
>>> person['children'] = ['Ralph', 'Betty', 'Joey']
>>> person['pets'] = {'dog': 'Fido', 'cat': 'Sox'}
  • value추출
>>> person['children']
['Ralph', 'Betty', 'Joey']

>>> person['children'][-1]
'Joey'
>>> person['pets']['cat']
'Sox'

불변의 값 KEY

A given key can appear in a dictionary only once. Duplicate keys are not allowed.

>>> d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
TypeError: unhashable type: 'list'


>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
>>> d[(1,1)]
'a'
>>> d[(2,1)]
'c'

Values

By contrast, there are no restrictions on dictionary values. Literally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects.

>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d
{0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d[0] == d[1] == d[2]
True

Built-in-Functions/Methods

  • in/not in
>>> MLB_team = {
...     'Colorado' : 'Rockies',
...     'Boston'   : 'Red Sox',
...     'Minnesota': 'Twins',
...     'Milwaukee': 'Brewers',
...     'Seattle'  : 'Mariners'
... }

>>> 'Milwaukee' in MLB_team
True
>>> 'Toronto' in MLB_team
False
>>> 'Toronto' not in MLB_team
True
  • len()
>>> len(MLB_team)
5
  • d.clear()
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}

>>> d.clear()
>>> d
{}
  • d.get(key)
    :사전에 키가 있는지 여부를 확인하지 않아도 오류를 발생시키지 않고 사전에서 키 값을 가져 오는 편리한 방법을 제공합니다.
>>> d = {'a': 10, 'b': 20, 'c': 30}

>>> print(d.get('b'))
20
>>> print(d.get('z'))
None

옵션 : 만약 키가 없으면 나올 값을 지정할 수도 있습니다. (default=-1 ,쉼표만입력)

>>> print(d.get('z', -1))
-1
  • d.items()
    : Returns a list of key-value pairs in a dictionary.
>>> list(d.items())
[('a', 10), ('b', 20), ('c', 30)]
>>> list(d.items())[1][0]
'b'
>>> list(d.items())[1][1]
20
  • d.keys()
    : Returns a list of keys in a dictionary.
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}

>>> list(d.keys())
['a', 'b', 'c']
  • d.values()
    : Returns a list of values in a dictionary.
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}

>>> list(d.values())
[10, 20, 30]


>>> d = {'a': 10, 'b': 10, 'c': 10}
>>> d
{'a': 10, 'b': 10, 'c': 10}

>>> list(d.values())
[10, 10, 10]

.items(), .keys(), and .values() 메소드는 실제로 view object(뷰 객체)라는 것을 반환합니다. dictionary view object는 keys와 values를 비추는 창과 같습니다.
실용적인 목적으로 이러한 메서드는 사전의 키 및 값 목록을 반환하는 것으로 생각할 수 있습니다.

  • d.pop(key,default)
    key 지우기
>>> d = {'a': 10, 'b': 20, 'c': 30}

>>> d.pop('b')
20
>>> d
{'a': 10, 'c': 30}

>>> d.pop('z', -1)
-1
>>> d
{'a': 10, 'b': 20, 'c': 30}
  • d.pipitem()
    마지막 딕셔너리 key,value 값 제거

>>> d.popitem()
('c', 30)
>>> d
{'a': 10, 'b': 20}

>>> d.popitem()
('b', 20)
>>> d
{'a': 10}

If d is empty, d.popitem() raises a KeyError exception:

>>> d = {}
>>> d.popitem()
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    d.popitem()
KeyError: 'popitem(): dictionary is empty'
  • d.update(obj)
  1. 딕셔너리에 없는 키의 경우
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d2 = {'b': 200, 'd': 400}

>>> d1.update(d2)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
  1. 같은 키가 이미 있을 경우
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update([('b', 200), ('d', 400)])
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}

>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update(b=200, d=400)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}

List vs Dictionary

List와 Dictionary는 비슷한 점이 많지만 요소들이 접근되는 방식이 다릅니다.
List는 (numerical) index를, Dictionary는 key를 통해 요소에 접근합니다.
이 서로 다른 특징을 각 상황에 적절하게 활용해 사용하면 됩니다.

profile
https://gggggeun.tistory.com/

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN