gpt4 book ai didi

Python:通过键获取字典中的值并用它们创建数组

转载 作者:行者123 更新时间:2023-12-02 18:27:15 25 4
gpt4 key购买 nike

我有一本这样的字典:

{
"0": {},
"1": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
"10": {},
"11": {},
"12": {
"PNR": "51313542"
},
"13": {},
"14": {},
"15": {
"PNR": "13151351351"
},
"16": {
"PNR": "13151351351"
},
"17": {
"PNR": "13151351351"
},
"18": {
"PNR": "13151351351"
},
"19": {
"PNR": "13151351351"
},
"20": {
"PNR": "13151351351"
},
"21": {
"PNR": "13151351351"
},
"22": {
"PNR": "13151351351"
},
"23": {
"PNR": "13151351351"
},
"24": {
"PNR": "13151351351"
}
}

我只想获取 PNR 并用它们创建一个数组。

我尝试通过此方法获取 PNR 值(将“输出”视为我的字典):

d_ = output.get("PNR")

但它没有给出任何结果。

无论我的字典中有多少个元素,如何获取 PNR 值并用它们创建一个数组?

最佳答案

您可以使用列表理解:

[v["PNR"] for v in dic.values() if "PNR" in v.keys()]

输出:

['51313542', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351', '13151351351']

关于Python:通过键获取字典中的值并用它们创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69980673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com