A
A
Archer1612020-07-31 16:13:07
Python
Archer161, 2020-07-31 16:13:07

Python. How to extract all the data of nested dictionaries that share the same key:value pair?

I extract data about films from film search. Faced a problem with extracting actors. Here is a snippet of the resulting JSON:

"$Film:927495.releaseOptions":{"isImax":false,"is3d":false,"__typename":"ReleaseOptions"},
"Person:3061538":{"id":3061538," name":"Taron Egerton","originalName":"Taron Egerton","__typename":"Person"},
"$Film:927495.members({\\"limit\\":10,\\"role\ \":[\\"ACTOR\\",\\"CAMEO\\",\\"UNCREDITED\\"]}).items.0":{"person":{"type":"id", "generated":false,"id":"Person:3061538","typename":"Person"},"__typename":"
"$Film:927495.members({\\"limit\\":10,\\"role\\":[\\"ACTOR\\",\\"CAMEO\\",\\"UNCREDITED\\ "]}).items.1":{"person":{"type":"id","generated":false,"id":"Person:514","typename":"Person"}," __typename":"FilmCrewMember"},
"Person:10315":{"id":10315,"name":"Ben Mendelsohn","originalName":"Ben Mendelsohn","__typename":"Person"},
"$ Film:927495.members({\\"limit\\":10,\\"role\\":[\\"ACTOR\\",\\"CAMEO\\",\\"UNCREDITED\\"] }).items.2":{"person":{"type":"id","generated":false,"id":"Person:10315","typename":"Person"},"__typename":"FilmCrewMember"},
"Person:1188127":{"id":1188127,"name":"Eve Hewson","originalName":" Eve Hewson","__typename":"Person"}

How to get all data of dictionaries that have a common pair: __typename":"Person"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PavelMos, 2020-07-31
@Archer161

Iterate through the elements of the first level through for i in dict, check the presence of the __typename key through dict1[i].keys() in it, if such a key exists, check its value.

import pprint
pprint.pprint (dict1)
for i in dict1:
    if '__typename' in dict1[i].keys():
        if dict1[i]['__typename']=='Person':
            print ('Match on: ',i)
            print (dict1[i])

If __typename: Person is in the elements of another level, the script needs to be redone, for example, first find out the maximum nesting of the element and then check for all levels

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question