Hashtables
Mon 30 June 2025
d = {}
d['a'] = 1
d['b'] = 2
print(d)
{'a': 1, 'b': 2}
print(d['a'])
1
d['c'] = 3
d['a'] = 100
print(d)
{'a': 100, 'b': 2, 'c': 3}
del d['b']
print(d)
{'a': 100, 'c': 3}
len(d)
2
d.get('a')
100
d.get('z', 'not found')
'not found'
'c' in d
True
'z' in d
False
d.keys()
dict_keys(['a', 'c'])
d.values()
dict_values([100, 3])
d.items()
dict_items([('a', 100), ('c', 3)])
for key in d: print(key)
a
c
for value in d.values(): print(value)
100
3
for k, v in d.items(): print(k, v)
a 100
c 3
dict1 = {'x': 1, 'y': 2}
dict2 = {'y': 3, 'z': 4}
dict1.update(dict2)
print(dict1)
{'x': 1, 'y': 3, 'z': 4}
dict3 = dict1.copy()
print(dict3)
{'x': 1, 'y': 3, 'z': 4}
dict3.clear()
print(dict3)
{}
dict4 = dict(a=1, b=2)
print(dict4)
{'a': 1, 'b': 2}
dict5 = {i: i**2 for i in range(5)}
print(dict5)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
tuple_key = (1, 2)
d[tuple_key] = 'tuple as key'
print(d)
{'a': 100, 'c': 3, (1, 2): 'tuple as key'}
try: print(d['missing'])
except KeyError: print('KeyError')
KeyError
default = d.setdefault('new', 999)
print(d)
{'a': 100, 'c': 3, (1, 2): 'tuple as key', 'new': 999}
print(default)
999
d.pop('new')
999
print(d)
{'a': 100, 'c': 3, (1, 2): 'tuple as key'}
d.popitem()
((1, 2), 'tuple as key')
print(d)
{'a': 100, 'c': 3}
from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
print(dd)
defaultdict(<class 'int'>, {'a': 1})
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
print(od)
OrderedDict({'a': 1, 'b': 2})
od.move_to_end('a')
print(od)
OrderedDict({'b': 2, 'a': 1})
od.popitem(last=False)
('b', 2)
print(od)
OrderedDict({'a': 1})
d = dict([('x', 10), ('y', 20)])
print(d)
{'x': 10, 'y': 20}
zipped = zip(['a', 'b'], [1, 2])
d = dict(zipped)
print(d)
{'a': 1, 'b': 2}
d = {chr(65+i): i for i in range(10)}
print(d)
{'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9}
d = {x: x+1 for x in range(10) if x % 2 == 0}
print(d)
{0: 1, 2: 3, 4: 5, 6: 7, 8: 9}
hash('abc')
-6797330088782940123
hash(123)
123
hash((1,2))
-3550055125485641917
d = {'a': {'nested': 1}}
print(d['a']['nested'])
1
d['a']['nested'] += 1
print(d)
{'a': {'nested': 2}}
d = {i: chr(65+i) for i in range(5)}
for k in sorted(d): print(k, d[k])
0 A
1 B
2 C
3 D
4 E
inverse = {v: k for k, v in d.items()}
print(inverse)
{'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4}
import json
json_str = json.dumps(d)
print(json_str)
{"0": "A", "1": "B", "2": "C", "3": "D", "4": "E"}
Score: 80
Category: basics