Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Search Dictionary by Key to return Value

I have a fairly complex dictionary with lists that I’m trying to use. I’m attempting to search the dictionary for the key "rows", which has a list.

With my current sample of data, I can easily pull it like so with index operator:

my_rows = my_dict['inputContent']['document']['fields'][2]['value']['rows']

‘rows’ is a list and those are the values I am trying to pull. However, my data from ‘rows’ won’t always be in the exact same location but it will always be in my_dict. It could be in a different index like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my_dict['inputContent']['document']['fields'][4]['value']['rows']

or

my_dict['inputContent']['document']['fields'][7]['value']['rows']

Really any number.

I’ve tried using just the basic:

my_rows = my_dict.get("rows")

But this returns None.

I find lots of articles on how to search for values and return key, but I know the key and it will always be the same, while my values in ‘rows’ will always be different.

I’m new to python and using dictionaries in general, but i’m really struggling to drill down into this dictionary to pull this list.

>Solution :

my_dict['inputContent']['document']['fields'][2]['value']['rows']
my_dict['inputContent']['document']['fields'][4]['value']['rows']
my_dict['inputContent']['document']['fields'][7]['value']['rows']

Looks like the overall structure is the same, the only variable is the numeric list index of the fourth element. So we need a loop that iterates over each element of that list:

for element in my_dict['inputContent']['document']['fields']:
    if 'rows' in element['value']:
        # found it!
        print(element['value']['rows']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading