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

How to access JSON information given one information, if the other is a 'sibling' to that one, rather than a child, in Python?

I have a JSON/dictionary object in Python that looks like the following:

object = {"participants":
    [
        {"name": "Tyler", "role": "CEO"},
        {"name": "Robin", "role": "analyst"}
        {"name": "James", "role": "manager"}
    ]
}

Given a persons name, how do I access their role? As the role is not a "sub-information" of the name, you can’t just do something like

object['participants']['Tyler']['role']

or something. You don’t know the index of the specific person either (I presume you can make a loop that finds it if that is the only solution), so you can’t just do

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

object['participants'][0]['role']

either, just because Tyler here happens to be at index 0.

>Solution :

I would use something like this:

def jobs_where_name_is(json_object, name):
    return {entry["role"] for entry in filter(lambda entry: entry["name"] == name, json_object["participants"])}

Note that there might be more then one person with the same name, that’s why a set of jobs is returned and not just one. There might be more than one person with the same name that work in the same job, so that’s why I used curly brackets (set) instead of square brackets (list). Note that object is a keyword in python, so it is discouraged to use it as a variable name.

By the way, if you are working with a very large databse, I would recommend perhaps checking out the pymongo library. That could greatly improve your performance since you can use mongodb queries natively.

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