Dictionary
- key value pairs
- unordered
- search, insert, delete -
O(1)
Initialize
- Python
d = {}
d = dict()
Insert
- Python
d["h"] = 20
warning
The dictionary key should be immutable. Use tuple instead of list.
Access
- Python
print(d["h"]) # 20
d.get("h", 0) # 0 is default value
for v in d.values()
for k in d.keys()
for k,v in d.items()
Delete
- Python
del d["h"] # delete
d.pop("h") # delete and return
d.popitem() # removes and returns the last inserted
Others
- Python
len(d)
if "h" in d
from collections import defaultdict
d = defaultdict(list)
tip
# use defaultdict(list) if values are list
# with defalutdict
d['fruits'].append('apple')
# without defaultdict
if 'fruits' not in d:
d['fruits'] = []
d['fruits'].append('apple')