Show Menu
Cheatography

Python Basics - Dictionaries and Sets Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Dictio­naries and Sets - Syntax

d = {'a': 1, 'b': 2, 'c': 3}
Dictio­naries are defined with {key1: value1, key2: value2, ...}
d['a']
Returns the value associated with 'a' (1)
d['a'] = 11
Changes value associated with 'a' to 11
d['d'] = 4
Adds 'd' key and associates it with 4 value

Dictio­naries - Methods

d1 = {'a': 1, 'b': 2, 'c': 3}
d2 = {'d': 4, 'e': 5, 'f': 6}
'a' in d1
Returns True if 'a' is in d1 and False otherwise (True)
d1.items()
Returns a list of (keys, values) in d1 (dict_­ite­ms(­[('a', 1), ('b', 2), ('c', 3)]))
d1.keys()
Returns a list of keys in d1 (dict_­key­s(['a', 'b', 'c']))
d1.val­ues()
Returns a list of values in d1 (dict_­val­ues([1, 2, 3]))
d1.upd­ate(d2)
Updates the values of existing keys in d1 with their respective in d2 and adds d2 keys and values that are not on d1
d1.get­('c')
1
Returns the value associated with 'c' and does nothing if 'c' is not on d1 (3)
d1.setdefault('3', 0)
Do the same as get(), but returns 0 if '3' is not on d1 (0)
d1.pop­('c')
Returns the value associated with 'c' and removes it from d1 (3)
d1.pop­item()
Returns the value associated with a key and removes it from d1 (3)
d1.clear()
Clears the dictionary entirely
d1.copy()
2
Returns a copy of d1
1 Using get() method prevents KeyError
2 The copy() method returns a dictionary identical to the original, but with a different ID. It means that they are allocated in different places of memory.

Dictio­naries - Loop Through Items

d = {'a': 1, 'b': 2, 'c': 3}

for i, j in d.items():
    print(f"Key: {i}, Value: {j}")
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

Dictio­naries - Loop Through Keys

d = {'a': 1, 'b': 2, 'c': 3}

for i in d.keys():
    print(f"Key: {i}")
Key: a
Key: b
Key: c

Dictio­naries - Loop Through Values

d = {'a': 1, 'b': 2, 'c': 3}

for i in d.values():
    print(f"Values: {i}")
Values: 1
Values: 2
Values: 3