astroball astroball - 21 days ago 8
Python Question

Python: Extract values from a dictionary embedded in another dictionary and list

An API I'm using outputs the coordinates of a face from a picture as follows:

[{'faceId': '59b5b8ad-ea77-455b-bdef-6044883bab6a',
'faceRectangle': {'left': 96, 'top': 51, 'width': 334, 'height': 334}}]


How can I extract the values from just the 'top' and 'left' keys (in this order)? I am looking for a simple output like this:

51
96

Answer

Let us assume that your list is named mydict

mydict = [{'faceId': '59b5b8ad-ea77-455b-bdef-6044883bab6a', 
'faceRectangle': {'left': 96, 'top': 51, 'width': 334, 'height': 334}}]

now mydict[0]['faceRectangle'] will return:

{'left': 96, 'top': 51, 'width': 334, 'height': 334}

So what you need is

mydict[0]['faceRectangle']['left']
mydict[0]['faceRectangle']['top']
Comments