python:什么是最好的方式来检查多个键存在于字典中? [英] python: what is best way to check multiple keys exists in a dictionary?
问题描述
我的字典看起来像
d = {
'name':'name',
'date':'date',
'amount':'amount',
...
}
我想测试如果名称
和金额
存在,所以我会在$ d $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
假设我从api获取数据,我想测试是否 10
字段存在于字典中。
仍然是寻找最好的方法?
您可以使用设置
交集:
如果不是d.viewkeys()& {'amount','name'}:
raise ValueError
在Python 3中, 'd be:
如果不是d.keys()& {'amount','name'}:
raise ValueError
因为 .keys()
默认情况下返回一个dict视图。 字典视图对象,例如由<$ c $在Python中,c。.viewkeys()(和 .keys()
3)作为集合和交集测试非常有效。
在Python 2.7中演示:
>>> d = {
...'name':'name',
...'date':'date',
...'amount':'amount',
...}
>>>不是d.viewkeys()& {'amount','name'}
False
>>> del d ['name']
>>>>不是d.viewkeys()& {'amount','name'}
False
>>> del d ['amount']
>>>不是d.viewkeys()& {'amount','name'}
True
请注意, 键都缺少。如果您需要测试,如果 缺少,请使用:
如果不是d.viewkeys ()> = {'amount','name'}:
raise ValueError
仅当 键存在时,这是False:
>>> d = {
...'name':'name',
...'date':'date',
...'amount':'amount',
...}
>>>不是d.viewkeys()> = {'amount','name'}
False
>>> del d ['amount']
>>>不是d.viewkeys()> = {'amount','name'})
True
对于严格比较(仅允许 两个键,不再更多,不少于),只需使用列表:
如果d.keys()!= ['amount','name']:
/ pre>
raise ValueError
my dict looks like
d = { 'name': 'name', 'date': 'date', 'amount': 'amount', ... }
I want to test if
name
andamount
exists, so I will doif not `name` in d and not `amount` in d: raise ValueError # for example
Suppose I get the data from an api and I want to test if
10
of the fields exists in the dictionary or not.Is it still the best way to look for?
解决方案You can use
set
intersections:if not d.viewkeys() & {'amount', 'name'}: raise ValueError
In Python 3, that'd be:
if not d.keys() & {'amount', 'name'}: raise ValueError
because
.keys()
returns a dict view by default. Dictionary view objects such as returned by.viewkeys()
(and.keys()
in Python 3) act as sets and intersection testing is very efficient.Demo in Python 2.7:
>>> d = { ... 'name': 'name', ... 'date': 'date', ... 'amount': 'amount', ... } >>> not d.viewkeys() & {'amount', 'name'} False >>> del d['name'] >>> not d.viewkeys() & {'amount', 'name'} False >>> del d['amount'] >>> not d.viewkeys() & {'amount', 'name'} True
Note that this tests True only if both keys are missing. If you need your test to pass if either is missing, use:
if not d.viewkeys() >= {'amount', 'name'}: raise ValueError
which is False only if both keys are present:
>>> d = { ... 'name': 'name', ... 'date': 'date', ... 'amount': 'amount', ... } >>> not d.viewkeys() >= {'amount', 'name'} False >>> del d['amount'] >>> not d.viewkeys() >= {'amount', 'name'}) True
For a strict comparison (allowing only the two keys, no more, no less), just use a list:
if d.keys() != ['amount', 'name']: raise ValueError
这篇关于python:什么是最好的方式来检查多个键存在于字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!