[英]Python: check if a key exists in a nested dict
I am trying to check if a certain key exists in a nested dict.我正在尝试检查嵌套字典中是否存在某个键。
eg:例如:
x = [{
'11': {
0: [
{
'bb_id': '122',
'cc_id': '4343'
}
],
1: [
{
'bb_id': '4334',
'cc_id': '3443'
},
{
'bb_id': '5345',
'cc_id': '257'
}
]
}
}]
I need to check if the key '11'
exists in x
, and further if the key 0
exists in the value of the key '11'
.我需要检查键
'11'
是否存在于x
中,以及键0
是否存在于键'11'
的值中。
I've tried doing:我试过做:
print(any(0 in d for d in x if '11' in d))
It seems this would achieve what you are trying to do:看来这将实现您正在尝试做的事情:
any(['11' in d.keys() and 0 in d['11'].keys() for d in x])
Explanation:解释:
x
;x
的每个字典;'11'
, and search its value (which is expected to be a dictionary too) for a key of 0
;'11'
的键,并在其值(也应该是字典)中搜索0
的键;True
;True
; else, return False
.False
。 In the question's comments, Sushanth has provided an even shorter and possibly more Pythonic way, using a generator and the dictionary's get()
method with an empty dictionary as a fallback value:在问题的评论中,Sushanth 提供了一种更短且可能更 Pythonic 的方式,使用生成器和字典的
get()
方法以及空字典作为后备值:
any(d.get('11', {}).get(0) for d in x)
What you have here is a list of dicts with values as a dict of lists of dicts.
您在这里拥有的是一个字典列表,其值作为字典列表的字典。
Try this one-liner list comprehension.试试这个单行列表理解。
x
here is a list of dicts (in this case with a single dict). x
这里是一个字典列表(在这种情况下是一个字典)。 The code below returns True for every dict that is in x
if '11' exists in its key
AND if 0 exists in the key of value of '11'
.如果
'11' exists in its key
中并且如果0 exists in the key of value of '11'
,则下面的代码为x
中的每个 dict 返回 True '11' 。 Only if both conditions are met, you get a TRUE
else FALSE
-只有当这两个条件都满足时,你才会得到一个
TRUE
else FALSE
-
True
else False
True
否则返回False
#Items to detect
a = '11'
b = 0
#Iterate of the nested dictionaries and check conditions
result = [(k==a and b in v.keys()) for i in x for k,v in i.items()]
print(result)
[True]
A raw way to do that could just be an if condition:一个原始的方法可能只是一个 if 条件:
if '11' in x[0]:
print("11 in x")
if 0 in x[0]['11']:
print("0 in 11")
You could also use a for loop:您还可以使用 for 循环:
for d in x:
if '11' in d:
print("11 in d")
if any(d['11']) and 0 in d['11']:
print("0 in 11")
has_key = lambda key, _dict: re.search("{%s" % str(key), str(_dict).replace(" ", ""))
I came up with another way to do it.我想出了另一种方法来做到这一点。
(d.get('key1') or {}).get('key2')
Our example:我们的例子:
(x[0].get('11') or {}).get(0)
Explanation of Steps:步骤说明:
x[0]
= Gets dictionary x[0]
= 获取字典
(x[0].get('11') or {})
= Tries and gets key '11'
key from dictionary x
; (x[0].get('11') or {})
= 尝试从字典x
中获取键'11'
键; if the key doesn't exist, then just set a blank dictionary {}
.如果密钥不存在,则只需设置一个空白字典
{}
。
(x[0].get('11') or {}).get(0)
= Remember .get()
on a dictionary will return None if the 0
doesn't exist rather than throw an error. (x[0].get('11') or {}).get(0)
= 记住,如果0
不存在,字典上的.get()
将返回 None 而不是抛出错误。
get(key[, default])
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method never raises a KeyError.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.