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
object['participants'][0]['role']
either, just because Tyler here happens to be at index 0.
CodePudding user response:
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.