Last modified on 25 Sep 2020.

Checking

# check if empty
bool(my_dict) # False if empty

Creating

# empty dict
my_dict = {}
# integer keys
my_dict = {1: "a", 2: 3}
# contains complicated types
my_dict = {1: ["1", "2"], "2": {1: 1, 2: 2}, 3: (1, 2)}

Updating

d = {1: "one", 2: "three"}
d1 = {2: "two"}

# update value of key "2"
d.update(d1)

# add new key "3"
d2 = {3: "three"}
d.update(d2)

Access elements

my_dict = {1: "a", 2: "b"}
my_dict[1]
my_dict.keys()
my_dict.values()
my_dict.items()
'a'
dict_keys([1, 2])
dict_values(['a', 'b'])
dict_items([(1, 'a'), (2, 'b')])
for key, val in my_dict.items():
  print(key, val)
1 a
2 b

If the key doesn’t exist, use the default!

dct = {1: 'a', 2: 'b'}
dct.get(1)
dct.get(3, 'c')
'a'
'c'

Sorted keys

for key in sorted(my_dict.keys()):
  pass

Notes with this notation aren't good enough. They are being updated. If you can see this, you are so smart. ;)