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

后端 未结 7 793
星月不相逢
星月不相逢 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:30

    Is this what you want:

    >>> d={'a':1,'b':2,'c':3}
    >>> default_val=99
    >>> for k in d:
    ...     d[k]=default_val
    ...     
    >>> d
    {'a': 99, 'b': 99, 'c': 99}
    >>> 
    
    >>> d={'a':1,'b':2,'c':3}
    >>> from collections import defaultdict
    >>> d=defaultdict(lambda:99,d)
    >>> d
    defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
    >>> d[3]
    99
    
    0 讨论(0)
  • 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 "<stdin>", line 1, in <module>
    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
    
    0 讨论(0)
  • 2020-12-02 12:33

    In case you actually mean what you seem to ask, I'll provide this alternative answer.

    You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict does. This will do so:

    class DictWithDefault(dict):
        def __init__(self, default, **kwargs):
            self.default = default
            super(DictWithDefault, self).__init__(**kwargs)
    
        def __getitem__(self, key):
            if key in self:
                return super(DictWithDefault, self).__getitem__(key)
            return self.default
    

    Use like this:

    d = DictWIthDefault(99, x=5, y=3)
    print d["x"]   # 5
    print d[42]    # 99
    42 in d        # False
    d[42] = 3
    42 in d        # True
    

    Alternatively, you can use a standard dict like this:

    d = {3: 9, 4: 2}
    default = 99
    print d.get(3, default)  # 9
    print d.get(42, default) # 99
    
    0 讨论(0)
  • 2020-12-02 12:36

    Not after creating it, no. But you could use a defaultdict in the first place, which sets default values when you initialize it.

    0 讨论(0)
  • 2020-12-02 12:47

    defaultdict can do something like that for you.

    Example:

    >>> from collections import defaultdict
    >>> d = defaultdict(list)
    >>> d
    defaultdict(<class 'list'>, {})
    >>> d['new'].append(10)
    >>> d
    defaultdict(<class 'list'>, {'new': [10]})
    
    0 讨论(0)
  • 2020-12-02 12:53

    Use defaultdict

    from collections import defaultdict
    a = {} 
    a = defaultdict(lambda:0,a)
    a["anything"] # => 0
    

    This is very useful for case like this,where default values for every key is set as 0:

    results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
    for k,v in results.iteritems():
      a['count'] += v['count']
      a['pass_count'] += v['pass_count']
    
    0 讨论(0)
提交回复
热议问题