2 Dictionaries
Last edited
16 get read from a dict with a fallback
Important
- When there is a sensible default, set it and continue as if you got the value
- Use a walrus
:=when the control flow will change
Demo of both options
# 1) Sensible default
count = counters.get(key, 0)
counters[key] += 1
# 2) Control flow must change
for attr in data:
if not (ts := attr.get("timestamp")): # guard clause
continue # there's no way to handle this, skip it
process(ts)
# Another example
if last_seen_iso:
timestamp = ... # preferred source
elif attr_ts := attr.get("timestamp"): # walrus, bind and test
timestamp = datetime.fromtimestamp(int(attr_ts), tz=timezone.utc)
else:
continue # neither, give upNote
How
.get()works:count = counters.get(key, 0) counters[key] += 1 # Under the hood this is what happens try: count = counters[key] except KeyError: count = 0 counters[key] += 1
17 setdefault/defaultdict when the lookup must create and insert a mutable default
When to use defaultdict? When you control the dict’s creation
class Visits:
def __init__(self):
self.data = defaultdict(set)
def add(self, country, city):
self.data[country].add(city)When to use setdefault when the dict is handed to you.
# In one set reads or creates a set and places it in the dict
# and then adds to the set
visits.setdefault('France', set()).add('Arles')Why doesn’t get work work
# this creates a new set and returns it
# but it just updates the brand new and never puts it in the dict
visits.get('France', set()).add('Arles')