简体   繁体   中英

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?

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"

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

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