Reputation: 11
I am trying to check if a certain key exists in a nested dict.
e.g:
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'
.
I've tried doing:
print(any(0 in d for d in x if '11' in d))
Upvotes: 0
Views: 5246
Reputation: 331
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].get('11') or {})
= Tries and gets key '11'
key from dictionary x
; 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.
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.
See Python docs here for .get()
Upvotes: 1
Reputation: 1064
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
;'11'
, and search its value (which is expected to be a dictionary too) for a key of 0
;True
; else, return 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:
any(d.get('11', {}).get(0) for d in x)
Upvotes: 3
Reputation: 1
has_key = lambda key, _dict: re.search("{%s" % str(key), str(_dict).replace(" ", ""))
Upvotes: 0
Reputation: 19322
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). 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'
. Only if both conditions are met, you get a TRUE
else FALSE
-
True
else 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]
Upvotes: 1
Reputation: 33
A raw way to do that could just be an if condition:
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 d in x:
if '11' in d:
print("11 in d")
if any(d['11']) and 0 in d['11']:
print("0 in 11")
Upvotes: 0