Reputation: 21
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
Upvotes: 0
Views: 50
Reputation: 869
+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. e.g:
>>> 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)
Upvotes: 2