【问题标题】:Printing the values in a nested dictionary in Python 2.x在 Python 2.x 中打印嵌套字典中的值
【发布时间】:2016-12-28 09:06:57
【问题描述】:

我的 Python 2.x 脚本中返回了一个字典类型变量,其中包含以下值:-

{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}}]}

我想要做的是为给定的键提取以下值:-

  • 'gender'(值为'female')
  • 'score'(值为'0.731059')
  • 'age'[max](值为'17')
  • 'age'[score](值为'0.983185)

我尝试了以下方法,但似乎没有返回我正在寻找的内容:

      if key == 'faces':                      
          for k, v in key:                    
              print(k['gender'], k['max'], k['age'][0], k['age'][1])    

关于如何访问和打印我感兴趣的值有什么建议吗?

【问题讨论】:

    标签: python json python-2.7 dictionary nested


    【解决方案1】:

    你有嵌套的字典和列表:

    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"])
    

    性别字典看起来像:

    {u'gender': u'FEMALE', u'score': 0.731059}
    

    所以我们使用键 "gender""score" 来获取值,年龄字典看起来像:

     {u'max': 17, u'score': 0.983185}
    

    我们再次使用 "max""score"

    键获取值

    【讨论】:

    • 完美。非常感谢。也感谢您的解释和回答
    【解决方案2】:

    这是一个有点复杂的字典。这是您提取所需值的方式:

    d 成为你的命令:

    key = 'faces'
    inner = d[key][0]
    print(inner['gender']['gender'], inner['gender']['score'], inner['age']['max'], inner['age']['score']) 
    

    输出:

    FEMALE 0.731059 17 0.983185
    

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2018-09-12
      • 2022-12-03
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多