thefragileomen thefragileomen - 3 months ago 15
JSON Question

Printing the values in a nested dictionary in Python 2.x

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:-


  • 'gender' (the value being 'female')

  • 'score' (the value being '0.731059')

  • 'age'[max] (the value being '17')

  • 'age'[score] (the value being '0.983185)



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?

Answer

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"