简体   繁体   中英

I can't figure out how to extract specific key:value pairs from a nested dictionary

I'm working with IBM Watson VisualRecognition service and when I submit a file to be analyzed, I received the following dict response:

<class 'dict'>
{'images': [{'source': {'type': 'file', 'filename': 'frame_00100.jpg'}, 
'dimensions': {'height': 1080, 'width': 1920}, 'objects': {'collections': 
[{'collection_id': 'a9081264-3000-4cbb-8cb8-9b11ad019460', 'objects': 
[{'object': 'Car', 'location': {'left': 1119, 'top': 532, 'width': 390, 
'height': 264}, 'score': 0.98179674}]}]}}]}

When I try to print the list of keys and values, this is what I get:

keys = resp.keys()
values = resp.values()
print(str(keys))
print(str(values))

dict_keys(['images'])
dict_values([[{'source': {'type': 'file', 'filename': 'frame_00100.jpg'}, 'dimensions': {'height': 
1080, 'width': 1920}, 'objects': {'collections': [{'collection_id': 'a9081264-3000-4cbb-8cb8- 
9b11ad019460', 'objects': [{'object': 'Car', 'location': {'left': 1119, 'top': 532, 'width': 390, 
'height': 264}, 'score': 0.98179674}]}]}}]])

My objective is to be able to reference a specific value on the response later on my code. For instance, I'd like to be able to find resp['left'], which should return 1119

+1 to @PhilippSelenium's suggestion:

You just have to navigate through the dicts and lists until you find your element. Using ipython is really helpful in this case: d.get("images")[0].get("objects").get("collections")[0].get("objects")[0].get("location").get("left")

There are other libraries like flatten_json which will allow you to access the nested object from a "flat" dict. eg:

>>> from flatten_json import flatten
>>> resp = {'images': [{'source': {'type': 'file', 'filename': 'frame_00100.jpg'}, 
... 'dimensions': {'height': 1080, 'width': 1920}, 'objects': {'collections': 
... [{'collection_id': 'a9081264-3000-4cbb-8cb8-9b11ad019460', 'objects': 
... [{'object': 'Car', 'location': {'left': 1119, 'top': 532, 'width': 390, 
... 'height': 264}, 'score': 0.98179674}]}]}}]}
>>> resp = flatten(resp)
>>> print(resp["images_0_objects_collections_0_objects_0_location_left"])
1119

But its likely best to learn to do tit the hard way before trying to use a library to make it easy for you (the hard way is also more performant)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM