needleinthehay.de

Define Defaults for Dictionaries

Default without updating the dict:

mydict = {}
name = mydict.get("name", "Holger")

print(name)
print(mydict)

# OUT:
# Holger
# {}

Default and also updating dict:

mydict = {}
name = mydict.setdefault("name", "Holger")

print(name)
print(mydict)

# OUT:
# Holger
# {'name': 'Holger'}

Default all keys with same value using collections.defaultdict():

(especially useful in combination with lists)

from collections import defaultdict

moves = [
("Bart", "rock"),
("Lisa", "paper"),
("Bart", "rock"),
("Millhouse", "scissors"),
("Bart", "rock"),
("Millhouse", "paper"),
]

person_moves = defaultdict(list)

for name, move in moves:
person_moves[name].append(move)

print(person_moves)

# OUT:
# defaultdict(<class 'list'>, {
# 'Bart': ['rock', 'rock', 'rock'],
# 'Lisa': ['paper'],
# 'Millhouse': ['scissors', 'paper']
# })