Python Dictionaries¶
Copying¶
Deep copying¶
Shallow copying¶
>>> a = {1:1}
>>> b = {2:2}
>>> c = dict({'a': a, 'b': b})
>>> a[3] = 3
>>> c
{'a': {1: 1, 3: 3}, 'b': {2: 2}}
Deep copying dicts¶
Does dict have key?¶
Nested get¶
- default fallback for
.get
isNone
- unlike
getattr
- which you have to explicitly provide a fallback
- unlike
Merge Dictionaries¶
Python 3.10: Set Union Notation
Before Python 3.10
Destructure dicts¶
In JS
Python can't do the same thing 😞
Given params = {'a': 1, 'b': 2}
itemgetter
list comprehension
assignment
key with the max value¶
d = {'a': 1, 'b': 3000, 'c': 0}
max(stats, key=d.get) # 'b'
max(stats, key=lambda key: d[key]) # 'b'
Sorting by keys¶
- Python 3.6+: sorted by insertion order
- to sort, convert to to
dict_items
- an iterator (kinda like a list of tuples)
same as
The Craziest Dict Expression¶
bool
is implemented as a special intTrue == 1 == 1.0
hash(True) == hash(1) == hash(1.0)
- dict is looking for a key that matches the same
__hash__
__eq__
- so it overrides the value
- keeps
True
as the key because that was the first key- no point in updating the key's representation if it's gonna be the same
defaultdict
¶
ChainMap¶
Maintaining a precedence chain of defaults¶
cli_args = {"debug": True}
defaults = {"debug": False}
config = ChainMap(cli_args, defaults)
config["debug"] # True
# looks for the key in cli_args and then in defaults
MappingProxyType
¶
- read-only immutable dictionaries
- not hashable
- unlike
namedtuple
- unlike
- example
- dict of internal state that you don't
from types import MappingProxyType
writable = {'one': 1, 'two': 2}
read_only = MappingProxyType(writable)
>>> read_only['one']
1
>>> read_only['one'] = 23
TypeError:
"'mappingproxy' object does not support item assignment"
# Updates to the original are reflected in the proxy:
>>> writable['one'] = 42
>>> read_only
mappingproxy({'one': 42, 'two': 2})
UserDict¶
When you want to modify the behaviour of the built-in dict???
Last update:
2023-04-24