The first argument provides the initial value for the default_factory
attribute; it defaults to None. If default_factory is not None, it is
called without arguments to provide a default value for the given key,
this value is inserted in the dictionary for the key, and returned.
dd_dict = defaultdict(dict)
dd_dict["Joel"]["City"] = "Seattle"
in you case, when you call dd_dict["Joel"]
, there is no such key in the dd_dict
, this raises a KeyError
exception. defaultdict
has __missing__(key)
protocol to handle this error, when it can not find the key, it will call the default_factory
without arguments to provide a default value for the given key.
so when you call dd_dict["Joel"]
, this will give you a dict {}
, then you add item ["City"] = "Seattle"
to the empty dict, someting like:
{}["City"] = "Seattle"