-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdictionary
More file actions
executable file
·64 lines (49 loc) · 1.36 KB
/
Copy pathdictionary
File metadata and controls
executable file
·64 lines (49 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
import types
import json
class dqdict(dict):
def __str__(self):
return json.dumps(self)
a = dqdict()
a['foo'] = 'bar'
a[3] = 'aux'
assert str(a) == '{"foo": "bar", "3": "aux"}'
def mutate(a):
'''Dictionaries are passed by reference. This mutates in the caller.'''
a['foo'] += 5
b = {'foo':-4}
mutate( b ) # value increments
mutate( dict(b) ) # To avoid mutation, pass a copy
b['bar'] = 1
b['baz'] = 2
b['bar'] = 2 # Does not change insertion order
del b['bar'] # But deleting and re-assigning does change order
b['bar'] = 3
expect = { 'foo': 1, 'baz': 2, 'bar': 3 }
assert b == expect
# Iterate over a dictionary. Keys are returned in insertion order.
for k, v in b.items():
assert v == expect[k]
for k in b.keys():
assert b[k] == expect[k]
for v in b.values():
pass
def slice_a_dict():
print("Demonstrate slicing a dictionay")
a = {'foo': 1, 'bar': 2, 'baz': 3}
keys = ['foo', 'baz']
print(f'a = {a}');
s = { k:a[k] for k in keys if k in a }
print(f'slice = {s}')
slice_a_dict()
a = { 'a': 1, 'b': 2}
assert {'a': 5, 'b': 2} == a | { 'a': 5} # | == "dictionary union operator"
assert {'a':1, 'b':3, 'c':0} == a | {'b':3, 'c':0}
a = types.SimpleNamespace({'foo': 3})
a.bar = 5
assert a.foo == 3
assert a.bar == 5
b = types.SimpleNamespace(foo=3)
b.bar = 5
assert b.foo == 3
assert b.bar == 5