Search for a key in a nested Python dictionary
dictionary, nested, python, recursion
Solution
You're close.
idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
if idnum in idnumber.keys(): # you can skip '.keys()', it's the default
calculate = some_function_of(idnumber[idnum])
break # if we find it we're done looking - leave the loop
# otherwise we continue to the next dictionary
else:
# this is the for loop's 'else' clause
# if we don't find it at all, we end up here
# because we never broke out of the loop
calculate = your_default_value
# or whatever you want to do if you don't find it
If you need to know how many `11`s there are as keys in the inner `dict`s, you can:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
This works because a key can only be in each `dict` once so you just have to test if the key exits. `in` returns `True` or `False` which are equal to `1` and `0`, so the `sum` is the number of occurences of `idnum`.
Problem
I have some Python dictionaries like this: ``` A = {id: {idnumber: condition},.... ``` e.g. ``` A = {1: {11 : 567.54}, 2: {14 : 123.13}, ..... ``` I need to search if the dictionary has any `idnumber == 11` and calculate something with the `condition`. But if in the entire dictionary doesn't have any `idnumber == 11`, I need to continue with the next dictionary. This is my try: ``` for id, idnumber in A.iteritems(): if 11 in idnumber.keys(): calculate = ...... else: break ```
Related problems
- Is there a query language for JSON?
- Access nested dictionary items via a list of keys?
- Find all occurrences of a key in nested dictionaries and lists
- Chained, nested dict() get calls in python
- How do I traverse and search a python dictionary?
- Searching for keys in a nested dictionary
- Python: Updating a value in a deeply nested dictionary