简体   繁体   中英

Get specific the nested key/values based on a condition from python nested dictionary

I'm stuck parsing the below python nested dictionary based on the nested key. I want to filter a key's value and return all the nested key/values related to that.

{ 'US': { 'Washington': {'Seattle': {1: {'name': 'John', 'age': '27', 'gender': 'Male'}}},
{ 'Florida': {'some city': {2: {'name': 'Marie', 'age': '22', 'gender': 'Female'}}},
{ 'Ohio': {'some city': {3: {'name': 'Luna', 'age': '24', 'gender': 'Female', 'married': 'No'}}},
{ 'Nevada': {'some city': {4: {'name': 'Peter', 'age': '29', 'gender': 'Male', 'married': 'Yes'}}}}}

For instance, filtering on gender "Male" should return the below:

US Washington Seattle 1 name:John age: 27

US Nevada somecity 4 name:Peter age: 29 married: Yes

Can you please suggest the best way to parse it. I tried to use contains within a loop that doesn't seem to work.

We can recursively explore the dict structure, keeping track of the path of keys at each point. When we reach a dict containing the target value, we yield the path and the content of the dict.

We can use this generator:

def recursive_search(dct, target, path=None):
    if path is None:
        path = []
    if target in dct.values():
        out = ' '.join(path) + ' ' + ' '.join(f'{key}:{value}' for key, value in dct.items())
        yield out
    else:
        for key, value in dct.items():
            if isinstance(value, dict):
                yield from recursive_search(value, target, path+[str(key)])

this way:

data = { 'US': { 'Washington': {'Seattle': {1: {'name': 'John', 'age': '27', 'gender': 'Male'}}},
 'Florida': {'some city': {2: {'name': 'Marie', 'age': '22', 'gender': 'Female'}}},
 'Ohio': {'some city': {3: {'name': 'Luna', 'age': '24', 'gender': 'Female', 'married': 'No'}}},
 'Nevada': {'some city': {4: {'name': 'Peter', 'age': '29', 'gender': 'Male', 'married': 'Yes'}}}}}


for match in recursive_search(data, 'Male'):
     print(match)
        
# US Washington Seattle 1 name:John age:27 gender:Male
# US Nevada some city 4 name:Peter age:29 gender:Male married:Yes

This Code Will work...

a_dict={ 'US': { 'Washington': {'Seattle': {1: {'name': 'John', 'age': '27', 'gender': 'Male'}}}, 'Florida': {'some city': {2: {'name': 'Marie', 'age': '22', 'gender': 'Female'}}}, 'Ohio': {'some city': {3: {'name': 'Luna', 'age': '24', 'gender': 'Female', 'married': 'No'}}}, 'Nevada': {'some city': {4: {'name': 'Peter', 'age': '29', 'gender': 'Male', 'married': 'Yes'}}}}}

for k,v in a_dict.items():
    for k1,v1 in v.items():
        for k2,v2 in v1.items():
            for k3,v3 in v2.items():
                if v3["gender"]=="Male":
                    string=""
                    for k4,v4 in v3.items():
                        string=string+ k4+":"+v4+" "
                    print(k,k1,k2,k3, string.strip())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM