Python: list() as default value for dictionary

后端 未结 1 1184
时光说笑
时光说笑 2020-12-14 07:04

I have Python code that looks like:

if key in dict:
  dict[key].append(some_value)
else:
  dict[key] = [some_value]

but I figure there shou

相关标签:
1条回答
  • 2020-12-14 07:30

    The best method is to use collections.defaultdict with a list default:

    from collections import defaultdict
    dct = defaultdict(list)
    

    Then just use:

    dct[key].append(some_value)
    

    and the dictionary will create a new list for you if the key is not yet in the mapping. collections.defaultdict is a subclass of dict and otherwise behaves just like a normal dict object.

    When using a standard dict, dict.setdefault() correctly sets dct[key] for you to the default, so that version should have worked just fine. You can chain that call with .append():

    >>> dct = {}
    >>> dct.setdefault('foo', []).append('bar')  # returns None!
    >>> dct
    {'foo': ['bar']}
    

    However, by using dct[key] = dct.get(...).append() you replace the value for dct[key] with the output of .append(), which is None.

    0 讨论(0)
提交回复
热议问题