简体   繁体   English

检查多个字典键是否匹配的最pythonic方法是什么

[英]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不存在键ace ,我不希望它抛出任何异常

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的代码点比aa

>>> 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 . bdf不是None

About get method关于get方法

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.

相关问题 将特定关键字附加到Dictionary的大多数pythonic方法 - Most pythonic way to append Dictionary with specific keys 检查多个变量是否不是None的最pythonic方法是什么? - What is the most pythonic way to check if multiple variables are not None? 构建此词典的最pythonic方法是什么? - What's the most pythonic way to build this dictionary? 检查对象是否为数字的最pythonic方法是什么? - What is the most pythonic way to check if an object is a number? 如何以pythonic方式检查字典的某些变量和特定键是否为None? - How to check if certain variables and specific keys of a dictionary are None in a pythonic way? 创建一个通过字典过滤的“For Loop”的最pythonic方法是什么? - What is the most pythonic way to create a 'For Loop' that filters through a dictionary? 使用空字典作为默认参数的最Pythonic方法是什么? - What is the most Pythonic way to use an empty dictionary as a default argument? 什么是使用(元素)列表作为字典中的键的Pythonic方法? - What is the Pythonic way to use (elements of) a list as keys in a dictionary? python:在字典中存在检查多个键的最佳方法是什么? - python: what is best way to check multiple keys exists in a dictionary? 在多次调用同一函数时重用数据的最pythonic方法是什么? - What is the most pythonic way to reuse data in multiple calls to same function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM