티스토리 뷰

반응형

Python dictionary는 Key - value 포맷으로 데이터를 저장합니다. 

Java에서는 hashmap / hashtable 과 유사합니다. 

 

Create dictionary 

d = {
    'test2':222,
    'test1':111,
    'test6':666,
    'test5':555,
    'test3':333,
    'test4':444
}

d2 = dict([
('test2',222),
('test1',111),
('test6',666),
('test5',555),
('test3',333),
('test4',444)
])



>>> print(f'd is {type(d)}')
>>> print(f'd2 is {type(d2)}')

# Print
d is <class 'dict'>
d2 is <class 'dict'>

 

Accessing data

>>> d['test2']
222
>>> d['test2']=2222
>>> d
{'test2': 2222, 'test1': 111, 'test6': 666, 'test5': 555, 'test3': 333, 'test4': 444}

 

Commonly used Built-in functions

# Pop value based on the key
>>> d.pop('test1')
111
# (test1,111) no longer exists
>>> d
{'test2': 2222, 'test6': 666, 'test5': 555, 'test3': 333, 'test4': 444}

# Get value based on the key 
>>> d.get('test2')
2222
>>> d
{'test2': 2222, 'test6': 666, 'test5': 555, 'test3': 333, 'test4': 444}

# Get only keys
>>> d.keys()
dict_keys(['test2', 'test6', 'test5', 'test3', 'test4'])

# Get (key,value) 
>>> d.items()
dict_items([('test2', 2222), ('test6', 666), ('test5', 555), ('test3', 333), ('test4', 444)])

 

Iterate through dictionary

# Only keys
>>> for key in d:
...     print(key)

test2
test6
test5
test3
test4

# Only values
>>> d.values()
dict_values([2222, 666, 555, 333, 444])


# Key and value
>>> for key, value in d.items():
...     print(f'key:value == {key}:{value}')
key:value == test2:2222
key:value == test6:666
key:value == test5:555
key:value == test3:333
key:value == test4:444

Sort dictionary

# Copy dict
>>> d3 = d.copy()
>>> d3
{'test2': 2222, 'test6': 666, 'test5': 555, 'test3': 333, 'test4': 444}

# sort based on value 
>>> dict(sorted(d3.items(), key = lambda kv:kv[1], reverse=True))
{'test2': 2222, 'test6': 666, 'test5': 555, 'test4': 444, 'test3': 333}

>>> dict(sorted(d3.items(), key = lambda kv:kv[1], reverse=False))
{'test3': 333, 'test4': 444, 'test5': 555, 'test6': 666, 'test2': 2222}


# Sort based on key
>>> dict(sorted(d3.items(), key = lambda kv:kv[0], reverse=False))
{'test2': 2222, 'test3': 333, 'test4': 444, 'test5': 555, 'test6': 666}

>>> dict(sorted(d3.items(), key = lambda kv:kv[0], reverse=True))
{'test6': 666, 'test5': 555, 'test4': 444, 'test3': 333, 'test2': 2222}

 

Defaultdict

일반 dict 와 다르게 key 값이 없어도 error를 리턴하지 않습니다. 

# Dictionary 
>>> testdict={}
>>> testdict[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1

# Defaultdict
>>> testdict2=defaultdict(int)
>>> testdict2[1]
0

List 에서 default dictionary 생성

>>> from collections import defaultdict

>>> dict1:dict = defaultdict(list)
>>> test = [('test1',1),('test2',2),('test3',3)]

>>> type(test)
<class 'list'>

>>> for k, v in test:
...     dict1[k].append(v)

>>> dict1
defaultdict(<class 'list'>, {'test1': [1], 'test2': [2], 'test3': [3]})
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함
반응형