如何将默认值设置为python中的一个dict对象的所有键? [英] How to set default value to all keys of a dict object in python?

查看:357
本文介绍了如何将默认值设置为python中的一个dict对象的所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以使用setdefault(key,value)为给定的键设置默认值,但是有没有办法在创建dict之后将所有键的默认值设置为某些值?



换句话说,我想让dict为每个我还没有设置的键返回指定的默认值。

解决方案

您可以使用 替换旧字典defaultdict

 >>> from collections import defaultdict 
>>>> d = {'foo':123,'bar':456}
>>> d ['baz']
追溯(最近的最后一次调用):
文件< stdin>,第1行,< module>
KeyError:'baz'
>>> d = defaultdict(lambda:-1,d)
>>> d ['baz']
-1

这里的诀窍 code> defaultdict 可以使用另一个 dict 进行初始化。这意味着
,您可以保留常规 dict 中的现有值:

 >>> d ['foo'] 
123


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 ?

Put it another way, I want the dict to return the specified default value for every key I didn't yet set.

解决方案

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

这篇关于如何将默认值设置为python中的一个dict对象的所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆