How to set default value to all keys of a dict object in python?

后端 未结 7 818
星月不相逢
星月不相逢 2020-12-02 12:24

I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ?

7条回答
  •  离开以前
    2020-12-02 12:31

    You can replace your old dictionary with a defaultdict:

    >>> from collections import defaultdict
    >>> d = {'foo': 123, 'bar': 456}
    >>> d['baz']
    Traceback (most recent call last):
      File "", line 1, in 
    KeyError: 'baz'
    >>> d = defaultdict(lambda: -1, d)
    >>> d['baz']
    -1
    

    The "trick" here is that a defaultdict can be initialized with another dict. This means that you preserve the existing values in your normal dict:

    >>> d['foo']
    123
    

提交回复
热议问题