Python - Dictionary Default Values And Handle Missing Keys
Last Updated: 1705Z 23SEP19
(Created: 1657Z 23SEP19)
Define default dictionary values and handle missing keys.
Signatures:
None
Examples:
# If key exists, then return value. Else return the default value
name = cowboy.get('name', 'The Man with No Name')
# If key exists, then return value. Else set cowboy['name'] to 'The Man with No Name'
# and return the value
name = cowboy.setdefault('name', 'The Man with No Name')
# Handle missing keys with defaultdict
from collections import defaultdict
student_grades = defaultdict(list)
grades = [
('elliot', 91),
('neelam', 98),
('bianca', 81),
('elliot', 88),
]
for name, grade in grades:
student_grades[name].append(grade)
print(student_grades)
# output: defaultdict(<class 'list'>, {'neelam': [98], 'bianca': [81], 'elliot': [91, 88]})
References: