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

后端 未结 2 1698
北恋
北恋 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(, {})
    >>> data['foo'].append(42)
    >>> data
    defaultdict(, {'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.

提交回复
热议问题