@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic (No. 3118 / 12833) Handle Missing Keys with setdefault() and defaultdict()
The setdefault() function is like get(), but also assigns an item to the dictionary if the key is missing:
I've tried.
http://ideone.com/N2bmsU
away_team = { 'Tuvok': 1, "B'Elanna" : 2 }
print(away_team)
seven = away_team.setdefault("7of9", 3)
print(away_team)
print(seven)
run
{"B'Elanna": 2, 'Tuvok': 1}
{"B'Elanna": 2, 'Tuvok': 1, '7of9': 3}
3
Recommended Posts