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

后端 未结 2 1697
北恋
北恋 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: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

提交回复
热议问题