Reputation: 1547
I have a dictionary type variable returned in my Python 2.x script that contains the below values:-
{u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
What I want to do is extract the following values for the given keys:-
I tried the below but it doesn't seem to return what I am looking for:
if key == 'faces':
for k, v in key:
print(k['gender'], k['max'], k['age'][0], k['age'][1])
Any suggestions on how I can access and print the values I am interested in?
Upvotes: 1
Views: 1461
Reputation: 180391
You have nested dicts and lists:
d = {u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
# iterate over the list of dict(s)
for dct in d["faces"]:
gender, age = dct['gender'], dct["age"]
print(gender["gender"], gender["score"], age["max"], age["score"])
The gender dict looks like:
{u'gender': u'FEMALE', u'score': 0.731059}
So we use the keys "gender" and "score" to get the values, the age dict looks like:
{u'max': 17, u'score': 0.983185}
Again we just grab the values using the keys "max" and "score"
Upvotes: 3
Reputation: 13510
It's a bit complex dict. This is how you extract the desired values:
Let d
be your dict:
key = 'faces'
inner = d[key][0]
print(inner['gender']['gender'], inner['gender']['score'], inner['age']['max'], inner['age']['score'])
Output:
FEMALE 0.731059 17 0.983185
Upvotes: 1