I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ?
Put it another way, I want the dict to return the specified default value for every key I didn’t yet set.
You can replace your old dictionary with a
defaultdict:The “trick” here is that a
defaultdictcan be initialized with anotherdict. This meansthat you preserve the existing values in your normal
dict: