Skip to main content

Dictionary

  • key value pairs
  • unordered
  • search, insert, delete - O(1)

Initialize

d = {} 
d = dict()

Insert

d["h"] = 20
warning

The dictionary key should be immutable. Use tuple instead of list.

Access

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

del d["h"] # delete
d.pop("h") # delete and return
d.popitem() # removes and returns the last inserted

Others

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')