我想用一线Python方法将JSON嵌套数组转换为Python嵌套列表。
以下是我的JSON嵌套数组的示例:
my_dict = {
"background": "This is a test text.",
"person": [
{"name": "Max", "tranx_info": [
{"tranx_date":"7/1/2020","amount": 82 },
{"tranx_date":"27/2/2017","amount":177 }]
},
{"name": "Lily", "tranx_info": [
{"tranx_date":"12/7/1989","amount": 165 },
{"tranx_date":"28/2/1998","amount": 200 },
{"tranx_date":"28/2/2098","amount": 34 }]
}
]
}
我假设这将是Python中的嵌套列表理解?到目前为止,我已经尝试过,但是只能将结果放入列表中:
tranx_date_result = [x["tranx_date"] for y in my_dict["person"] for x in y["tranx_info"]]
#output
>>> ["7/1/2020","27/2/2017","12/7/1989","28/2/1998","28/2/2098"]
我希望"tranx_date"
结果出现在嵌套列表中;像这样的东西:
tranx_date_result = [["7/1/2020","27/2/2017"],["12/7/1989","28/2/1998","28/2/2098"]]
任何帮助表示赞赏:)
只需使用嵌套列表推导:
>>> [[x["tranx_date"] for x in y["tranx_info"]] for y in my_dict["person"]]
[['7/1/2020', '27/2/2017'], ['12/7/1989', '28/2/1998', '28/2/2098']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句