The best way for dict of lists is:
my_dict.setdefault(key,list()).append(value)
that is equivalent for
if not key in my_dict:
my_dict[key] = list()
nested_list = my_dict[key]
nested_list.append(value)
Thist is safe when my_dict doesnt have any list at key.
In earlier proposed variant:
my_dict[key].append(value)
which is equivalent for
nested_list = my_dict[key]
nested_list.append(value)
KeyError
will be raised if my_dict has no item at key
But if my_dict[key] has no 'append' method AttributeError
would be raised in both variants
UPD (important!): in construction like my_dict.setdefault(key,list())
a list
instance is created even if my_dict
has key
!