我有一个名为blob
的嵌套词典,如下所示:
{
"/var/log": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"},
"/opt": {"vgsize": "9.32g","vgname": "VolGroupOpt","desired_lv_size": "50"}
"/tmp": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"}
}
我需要:为每个desired_lv_size
获取vgname
的总和。
我将如何应对这一挑战?
我开始尝试:
set(blob.values())
可能会提取唯一的vgname
。但那给了我:
TypeError: unhashable type: 'dict'
答案 0 :(得分:4)
from collections import Counter
c = Counter()
for v in data.values():
c[v['vgname']] += int(v["desired_lv_size"])
答案 1 :(得分:2)
您可以执行以下操作
from collections import defaultdict
data = {
"/var/log": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"},
"/opt": {"vgsize": "9.32g","vgname": "VolGroupOpt","desired_lv_size": "50"},
"/tmp": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"}
}
res = defaultdict(int)
for d in data.values():
group = d.get("vgname")
value = float(d.get("desired_lv_size"))
res[group] += value
print(res)
# defaultdict(<class 'int'>, {'VolGroup': 40.0, 'VolGroupOpt': 50.0})
答案 2 :(得分:0)
假设 desired_lv_size值是整数,这将起作用:
x={
"/var/log": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"},
"/opt": {"vgsize": "9.32g","vgname": "VolGroupOpt","desired_lv_size": "50"},
"/tmp": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"}
}
totals={}
for f, f_data in x.items():
v=int(f_data["desired_lv_size"])
if f_data["vgname"] in totals:
totals[f_data["vgname"]]+=v
else:
totals[f_data["vgname"]]=v
for vgname, total in totals.items():
print("{0} total={1}".format(vgname, total))
答案 3 :(得分:0)
我会遍历字典的值并将desired_lv_size
条目添加到每个vgname
键入的字典中,如下所示:
vg_sizes = {}
for vg_dict in blob.values():
size = vg_sizes.setdefault(vg_dict['vgname'], 0)
vg_sizes[vg_dict['vgname']] = size + int(vg_dict['desired_lv_size'])
vg_sizes
最终为所有'vgname'
键入的词典,其值为所有'desired_lv_size'
的总和。
答案 4 :(得分:0)
blob = {
"/var/log": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"},
"/opt": {"vgsize": "9.32g","vgname": "VolGroupOpt","desired_lv_size": "50"},
"/tmp": {"vgsize": "46.27g","vgname": "VolGroup","desired_lv_size": "20"}
}
a = {}
for value in blob.values():
if value["vgname"] in a:
a[value["vgname"]] += int(value["desired_lv_size"])
else:
a[value["vgname"]] = int(value["desired_lv_size"])
a
是必需的词典。
这种方法只使用一个dict来存储最终结果,没有额外的导入,也没有并发症。