-
[Python] - Dictionary개발/Python 2022. 7. 27. 12:17
Dictionary
type is immutable key and mutable value mapping not sorted set
No index , so access the key- Syntax
# Default type {"a" : 1, "b":2} e = {} f = dict() newdict = dict( alice = 5, bob = 20, tony= 15, suzy = 30)
- Key is not allowed mutable key like list , set , dict
# Error case a = { {1, 3}: 5, {3,5}: 3} #set a = {[1,3]: 5, [3,5]: 3} #list a = { {"a":1}: 5, "abc": 3} #dict
# Key immuttable a = {1: 5, 2: 3} # int 사용 a = {(1,5): 5, (3,3): 3} # tuple사용 a = { True: 5, "abc": 3} # bool 사용
- list of list and list of tuple and tuple of list and tuple of tuple can changed the dictionary
name_and_ages = [['alice', 5], ['Bob', 13]] name_and_ages = [('alice', 5), ('Bob', 13)] name_and_ages = (('alice', 5), ('Bob', 13)) name_and_ages = (['alice', 5], ['Bob', 13]) # all case change the dict dict(name_and_ages)
복사
shallow copy
얕은 복사는 동일한 주소를 할당 받기 때문에 변경된다.
a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30} b =a.copy() c = dict(a) a['alice'].append(5) # change b['alice'] / c['alice'] # why? allocated same address
deep copy
import copy a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30} b = copy.deepcopy(a)
Dictionary function
a = {'alice': [1, 2, 3], 'bob': 20, 'tony': 15, 'suzy': 30} # key a.keys() # value a.values() # key-value a.items() # Passing value if key does not exist a.get( 'alice' , 0 ) > [1, 2, 3] a.get( 'tt' , 0 ) > 0 # dictionary 'in' use key 'alice' in a > True # delete key del a['alice']
Defaultdict
- Dictionary key에 대한 Value 초기화 값 설정 할 때 사용한다.
from collections import defaultdict a = defaultdict(int) a[1] > 0 a = defaultdict(lambda :3 ) a[1] > 3
'개발 > Python' 카테고리의 다른 글
[Python] - Powerful Function (0) 2022.07.27 [Python] - Set (0) 2022.07.27 [Python] - Tuple (0) 2022.07.27 [Python] - List (0) 2022.07.27 삼항 연산자(Ternary operator) (0) 2022.07.18