[英]What is most pythonic way to check if multiple dictionary keys match
Suppose I have a dictionary my_dict
.假设我有一本字典
my_dict
。
What is the most pythonic way to check if my_dict['a'] == 'b' and my_dict['c'] == 'd' and my_dict['e'] == 'f'
?检查
my_dict['a'] == 'b' and my_dict['c'] == 'd' and my_dict['e'] == 'f'
什么?
I do not want it to throw any exception if the keys a
, c
or e
don't exist in my_dict
如果
my_dict
不存在键a
、 c
或e
,我不希望它抛出任何异常
You can form a tuple with Map and compare it.您可以使用 Map 形成一个元组并进行比较。 By Mapping the get method, missing keys will produce a None value and not crash.
通过映射 get 方法,丢失的键将产生一个 None 值并且不会崩溃。
(*map(my_dic.get,('a','c','e'),) == ('b','f','d')
You can zip values and keys together and use get()
in a generator expression passed to all
:您可以将值和键压缩在一起,并在传递给
all
的生成器表达式中使用get()
:
my_dict = {'a':'b', 'c':'d','e':'f'}
keys = ['a', 'c', 'e']
vals = ['b', 'd', 'f']
all(my_dict.get(k) == v for k, v in zip(keys, vals))
# true
This assumes values are not None
, since get()
returns None
for missing values.这假设值不是
None
,因为get()
为缺失值返回None
。 If that's important, you can check for inclusion as well.如果这很重要,您也可以检查是否包含在内。
This will be False
when keys are missing or values are different like:当键丢失或值不同时,这将是
False
,例如:
my_dict = {'c':'d','e':'f'}
keys = ['a', 'c', 'e']
vals = ['b', 'd', 'f']
all(my_dict.get(k) == v for k, v in zip(keys, vals))
#False
Since this is a very simple use case, where the desired values have near identical character codes to the keys, you can use ord
to get the numeric code point or ordinal for a single-character string, and chr
to convert it back to a single-character string.由于这是一个非常简单的用例,其中所需的值具有与键几乎相同的字符代码,因此您可以使用
ord
获取单字符串的数字代码点或序数,并使用chr
将其转换回单个- 字符串。
Note that the code point of b
is one higher than a
, for example.请注意,例如,
b
的代码点比a
高a
。
>>> my_dict = {'a': 'b', 'c': 'd', 'e': 'f'}
>>> keys = ['a', 'c', 'e']
>>> all(my_dict.get(k) == chr(ord(k) + 1) for k in keys)
True
A similar approach using map
, adapted from the answer above:使用
map
的类似方法,改编自上述答案:
>>> list(map(my_dict.get, keys)) == [chr(ord(k) + 1) for k in keys]
True
I'll try to provide most understand-friendly and simple code at my opinion:我会尽量提供我认为最容易理解和简单的代码:
if my_dict.get('a') == 'b' and my_dict.get('c') == 'd' and my_dict.get('e') == 'f':
print('all keys exist and values are correct')
else:
print('one of keys is not exist or value of at least one key is not correct')
my_dict.get(key_name)
return None
if key_name
not exist. my_dict.get(key_name)
如果key_name
不存在则返回None
。 b
, d
and f
are not None
. b
, d
和f
不是None
。
Also you can catch error:您也可以捕获错误:
try:
if my_dict['a'] == 'b' and my_dict['c'] == 'd' and my_dict['e'] == 'f':
print('all keys exist and values are correct')
else:
print('all keys exist but some of values are not correct')
except KeyError:
print('some of keys are not exist')
It is so basic but... I guess it is should be here because it basic它是如此基本但是......我想它应该在这里,因为它是基本的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.