如何在另一个列表的列表中从字典中选择某个关键字



我有一个嵌套的JSON文件,如下所示:

[
{
"IsRecentlyVerified": true,
"AddressInfo": {
"Town": "Haarlem",
},
"Connections": [
{
"PowerKW": 17,
"Quantity": 1
}
],
"NumberOfPoints": 1,
},
{
"IsRecentlyVerified": true,
"AddressInfo": {
"Town": "Haarlem",
},
"Connections": [
{
"PowerKW": 17,
"Quantity": 1
},
{
"PowerKW": 17,
"Quantity": 1
}
],
"NumberOfPoints": 1,
}
]

正如您所看到的,这个JSON文件的列表由两个字典组成,每个字典都包含另一个列表(="Connections"(,该列表至少由一个字典组成。在这个JSON文件的每个字典中,我想选择所有名为"的键;数量;用它的值求和(所以在上面的示例代码中,我想计算总共有3个量(。

有时;数量;并不总是存在,所以这就是为什么我使用in来检查它是否存在。我注意到它现在只有找到密钥";数量;当我提到索引时,像这样:if "Quantity" in ev_list[info]["Connections"][0]

def amountOfChargingStations():
totalAmountOfChargingPolesInCity = 0
for info in range(len(ev_list)):
if "Town" in ev_list[info]["AddressInfo"]:
if ev_list[info]["AddressInfo"]["Town"] == "Haarlem":
totalAmountOfChargingStationsInCity = totalAmountOfChargingStationsInCity + 1
if "Quantity" in ev_list[info]["Connections"][0]:
if ev_list[info]["Connections"]:
for pole in ev_list[info]["Connections"]:
totalAmountOfChargingPolesInCity = totalAmountOfChargingPolesInCity + pole["Quantity"]
else:
print("Can't find connection")
print("There are at least", totalAmountOfChargingPolesInCity, "charging poles available.")
polesAndStations = amountOfChargingStations()

问题是它现在只使用每个"的第一个字典;"连接"-列表来求和。如何选择所有名为";数量;为了得出这个总数,而不知道每个"词典"中词典的总数;"连接"-列表(总金额从1到超过10不等(。有类似[0:end]的东西吗?

作为一个oneliner:

total_quantity = sum([con['Quantity'] for dataset in data for con in dataset['Connections'] if 'Connections' in dataset.keys() and 'Quantity' in con.keys() ])

给定data是您导入的json。


EDIT:抱歉,没有仔细阅读您的代码。

实际上,您不需要对一个范围内的for循环如此复杂,听起来就像您来自另一种编程语言。带

for info in ev_list
...

您已经获得了元素本身,并且可以将ev_list[info]更改为info

你也从其他地方得到了城市充电站的总数量吗?它应该像这样返回一个"赋值错误前引用"。

我仍然是一句俏皮话和列表综合的粉丝,所以这对我来说很有用:

def amountOfChargingStations():
total_amount_of_charging_poles_in_city = 0
total_amount_of_charging_stations_in_city = 0
for info in ev_list:
if "Town" in info["AddressInfo"]:
if info["AddressInfo"]["Town"] == "Haarlem":
total_amount_of_charging_stations_in_city = total_amount_of_charging_stations_in_city + 1
total_amount_of_charging_poles_in_city += sum(
[con.get('Quantity', ) for con in info.get('Connections', [])])
print("There are at least", total_amount_of_charging_poles_in_city, "charging poles available.")

第二版:对不起,我的错误,改变了我的理解。dictionary.get('key','default if key不在dictionary'(是从字典中调用某些内容的更安全的方法。

您可以尝试递归:

import json

def get_quantity(o):
if isinstance(o, dict):
if "Quantity" in o:
yield o["Quantity"]
for v in o.values():
yield from get_quantity(v)
elif isinstance(o, list):
for v in o:
yield from get_quantity(v)

with open("your_file.json", "r") as f_in:
data = json.load(f_in)
print(sum(get_quantity(data)))

打印:

3

这里有一个简单的方法,给定所描述的JSON结构,它可以根据需要工作:

quantity = 0
for d in json.loads(JDATA):
if (_list := d.get('Connections')):
for _d in _list:
quantity += _d.get('Quantity', 0)
print(quantity)

输出:

3

使用jmespath你可以得到金额作为

import jmespath
print(sum(jmespath.search("[*].Connections[].Quantity", data), 0))

相关内容

  • 没有找到相关文章

最新更新