initialize and add value to a list in dictionary at one step in Python 3.7

后端 未结 2 1696
北恋
北恋 2021-01-23 16:45

I have a dictionary where key is string and value is list.

Now while adding a value associated with given key, I always have to check if there is any list yet, otherwise

相关标签:
2条回答
  • 2021-01-23 17:28

    There are at least three ways:

    Use dict.setdefault

    >>> data = {}
    >>> data.setdefault('foo', []).append(42)
    >>> data
    {'foo': [42]}
    

    Use defaultdict, which unlike .setdefault, takes a callable:

    >>> from collections import defaultdict
    >>> data = defaultdict(list)
    >>> data
    defaultdict(<class 'list'>, {})
    >>> data['foo'].append(42)
    >>> data
    defaultdict(<class 'list'>, {'foo': [42]})
    

    Finally, subclass dict and implement __missing__:

    >>> class MyDict(dict):
    ...     def __missing__(self, key):
    ...         self[key] = value  = []
    ...         return value
    ...
    >>> data = MyDict()
    >>> data['foo'].append(42)
    >>> data
    {'foo': [42]}
    

    Note, you can think of the last one as the most flexible, you have access to the actual key that's missing when you deal with it. defaultdict is a class factory, and it generates a subclass of dict as well. But, the callable is not passed any arguments, nevertheless, it is sufficient for most needs.

    0 讨论(0)
  • 2021-01-23 17:43

    You can use dict.setdefault:

    >>> d = {}
    >>> d.setdefault('k', []).append(1)
    >>> d
    {'k': [1]}
    >>> d.setdefault('k', []).append(2)
    >>> d
    {'k': [1, 2]}
    

    Help on method_descriptor in dict:

    dict.setdefault = setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

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