mdekkers
mdekkers

Reputation: 622

retreive key from nested dict based on value, where key names are unknown

I have the following dict:

{
  'foo': {
    'name': 'bar',
    'options': None,
    'type': 'qux'
  },
  'baz': {
    'name': 'grault',
    'options': None,
    'type': 'plugh'
  },
}

The names of the top level keys are unknown at runtime. I am unable to figure out how to get the name of the top level key where the value of type is plugh. I have tried all kinds of iterators, loops, comprehensions etc, but i'm not great with Python. Any pointers would be appreciated.

Upvotes: 0

Views: 357

Answers (4)

Menglong Li
Menglong Li

Reputation: 2255

Besides running loop to filter the target, you have another option to use jsonpath, which is quite like xPath

# pip install jsonpath-ng==1.5.2
# python 3.6
from jsonpath_ng.ext import parse

dct = {
    'foo': {
        'name': 'bar',
        'options': None,
        'type': 'qux'
    },
    'baz': {
        'name': 'grault',
        'options': None,
        'type': 'plugh'
    },
}

parse_str = '$[[email protected]="plugh"]'
jsonpath_expr = parse(parse_str)
jsonpath_results = jsonpath_expr.find(dct)
if len(jsonpath_results) > 0:
    result = jsonpath_results[0].value
    print(result)
    # {'name': 'grault', 'options': None, 'type': 'plugh'}
else:
    result = None

Ref: https://pypi.org/project/jsonpath-ng/ to find out more stynax about jsonpath

Upvotes: 1

sarartur
sarartur

Reputation: 1228

Try this:

for key, inner_dict in dict_.items():
    if inner_dict['type'] == 'plugh':
        print(key)

Or if you a one liner to get the first key matching the condition:

key = next(key for key, inner_dict in dict_.items() if inner_dict['type'] == 'plugh')
print(key)

output:

baz

Upvotes: 2

Eugene K
Eugene K

Reputation: 86

You need to iterate over your data like this:

def top_level_key(search_key, data):
    for key, value in data.items():
        if value['type'] == search_key:
            return key

print(top_level_key('plugh', data_dict))

Upvotes: 1

Epsi95
Epsi95

Reputation: 9047

Try iterating over the dict keys and check for the element

for key in d:
    if(d[key]['type'] == 'plugh'):
        print(key)
baz

Upvotes: 1

Related Questions