从JSON字典(Python)中的列表中提取值



我需要从字典、列表和字典中提取一个值
我想要得到的值是affectedDeals中的dealId。(用^突出显示(

data = {'date': '2022-11-04T12:36:57.016', 'status': 'OPEN', 'reason': 'SUCCESS', 'dealStatus': 'ACCEPTED', 'epic': 'SILVER', 'dealReference': 'o_0bc30104-8ddf-4d67-9daa-e7d878a8cad9', 'dealId': '006011e7-0055-311e-0000-000080507631', 'affectedDeals': [{'dealId': '006011e7-0055-311e-0000-000080507633', 'status': 'OPENED'}], 'level': 20.138, 'size': 1.0, 'direction': 'BUY', 'guaranteedStop': False, 'trailingStop': False}                                                                                                                                                                                                       
                                                                                                                                                                                                   ^
output = 006011e7-0055-311e-0000-000080507633

这可能有助于您获得问题中预期的输出

代码:

data = {
"date": "2022-11-04T12:36:57.016",
"status": "OPEN",
"reason": "SUCCESS",
"dealStatus": "ACCEPTED",
"epic": "SILVER",
"dealReference": "o_0bc30104-8ddf-4d67-9daa-e7d878a8cad9",
"dealId": "006011e7-0055-311e-0000-000080507631",
"affectedDeals": [
{"dealId": "006011e7-0055-311e-0000-000080507633", "status": "OPENED"}
],
"level": 20.138,
"size": 1.0,
"direction": "BUY",
"guaranteedStop": False,
"trailingStop": False,
}
[i.get("dealId") for i in data.get("affectedDeals")]

输出:

006011e7-0055-311e-0000-000080507633

输出将包含在列表中,您可以使用索引从下面的列表中检索数据

lst = [i.get("dealId") for i in data.get("affectedDeals")]
lst[0] 

尝试这样做:

data = {'date': '2022-11-04T12:36:57.016', 
'status': 'OPEN',
'reason': 'SUCCESS',
'dealStatus': 'ACCEPTED',
'epic': 'SILVER',
'dealReference': 'o_0bc30104-8ddf-4d67-9daa-e7d878a8cad9',
'dealId': '006011e7-0055-311e-0000-000080507631',
'affectedDeals': [
{'dealId': '006011e7-0055-311e-0000-000080507633',
'status': 'OPENED'
}
],
'level': 20.138,
'size': 1.0,
'direction': 'BUY',
'guaranteedStop': False,
'trailingStop': False
}                                                                                                                                                                                            
print(data['affectedDeals'][0]['dealId'])
# Output: 006011e7-0055-311e-0000-000080507633

我们基本上访问了列表(affectedDeals(,然后选择了第0个索引,这也是一个字典,所以我们访问了指定的密钥(dealID(,然后打印它。

希望能有所帮助

相关内容

  • 没有找到相关文章

最新更新