【问题标题】:How to fetch values from json response in python having a dictionary containing list of dictionary?python - 如何在具有包含字典列表的字典的python中从json响应中获取值?
【发布时间】:2020-06-08 11:20:35
【问题描述】:

我需要获取一个值,例如,如果动物是狗,那么我需要它的 id

 {'findSomething': [{'Name': 'Andrew', 'id': '321Z4', 'animal': Dog }, {'Name': 'Andrew', 'id': '31Z45', 'animal': Cat }]}

【问题讨论】:

  • res[0] 知道它的第一行,但在我的情况下,我不确定动物会在第一行或其他,这就是为什么我会检查动物并获取相应的 id跨度>
  • Dog 是一个字符串(在这种情况下你错过了引号),还是一个对象?
  • res=your_dict.get('findSomething') print([x.get('id') for x in res if x.get('animal')=='Dog']),假设 Dog 是一个字符串
  • 据我所知,JSON需要双引号...
  • 你可以使用json.load/loads将json加载到字典中,或者使用response.json()

标签: python json python-3.x python-requests python-requests-html


【解决方案1】:

试试这个:

data =  {'findSomething': [{'Name': 'Andrew', 'id': '321Z4', 'animal': 'Dog' }, {'Name': 'Andrew', 'id': '31Z45', 'animal': 'Cat' }]}
res = [x['id'] for x in data['findSomething'] if x['animal'] == 'Dog']
print(res) #['321Z4']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多