adama
adama

Reputation: 557

Python filter nested dict with key value and print a part

Let´s say I have a nested dict like this but much longer:

    {
"problems": [{
                "1":[{
                        "name":"asprin abc",
                        "dose":"",
                        "strength":"100 mg"
                    }],


                "2":[{

                        "name":"somethingElse",
                        "dose":"",
                        "strenght":"51g"

                    }],
                "3":[{

                        "name":"againSomethingElse",
                        "dose":"",
                        "strenght":"511g"

                    }],           
        }],
        "labs":[{
            "missing_field": "missing_value"
        }]
    }

Now I want to iterate through the dict and do some filtering. I just want to have the part where the key "name" is LIKE '%aspirin%, as in Transact-SQL.

So the output should be the following:

[{
  "name":"asprin abc",
  "dose":"",
  "strength":"100 mg"
}]

I now how to iterate through the dict but I don´t know how I should achieve the value filtering where I print the whole part where the title matches.

Upvotes: 0

Views: 166

Answers (3)

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

You can try this below:

for p_obj in json_data["problems"]:
    for i in p_obj.keys():
        for j in p_obj[i]:
            if "asprin" in j["name"]:
                output.append(j)
print(output)

Upvotes: 0

Booboo
Booboo

Reputation: 44213

The following is a general solution making no assumption on the structure of the passed object, which could be a list, dictionary, etc. It will recursively descend throug the structure looking for a dictionary with a key "name" whose value contains asprin and will yield that dictionary:

d = {
"problems": [{
                "1":[{
                        "name":"asprin abc",
                        "dose":"",
                        "strength":"100 mg"
                    }],


                "2":[{

                        "name":"somethingElse",
                        "dose":"",
                        "strenght":"51g"

                    }],
                "3":[{

                        "name":"againSomethingElse",
                        "dose":"",
                        "strenght":"511g"

                    }],
        }],
        "labs":[{
            "missing_field": "missing_value"
        }]
    }

def filter(obj):
    if isinstance(obj, list):
        for item in obj:
            yield from filter(item)
    elif isinstance(obj, dict):
        if "name" in obj and "asprin" in obj["name"]:
            yield obj
        else:
            for v in obj.values():
                if isinstance(v, (list, dict)):
                    yield from filter(v)

print(list(filter(d)))

Prints:

[{'name': 'asprin abc', 'dose': '', 'strength': '100 mg'}]

Python Demo

Upvotes: 1

adama
adama

Reputation: 557

I found an easier solution like described above. A list comprehension is much easier

[problem for problem in problem['problems'] if problem['name'].find("aspirin")!=1]

Upvotes: 0

Related Questions