如何在python中找到列表中字典匹配键值的平均值


[{"name": "thisisname1", "filebytestotal": 334632,"memorybytes": 5467234},    
{"name": "thisisname2", "filebytestotal": 2351, "memorybytes": 324523},    
{"name": "thisisname3", "filebytestotal": 2314651, "memorybytes": 2235},    
{"name": "thisisname1", "filebytestotal": 13432, "memorybytes": 546534},    
{"name": "thisisname1", "filebytestotal": 32342, "memorybytes": 341234}]

大家好,我试图弄清楚如何为所有匹配的"name"值获得密钥filebytes和memorybytes的平均值。我的问题是,我不知道如何通过字典在总列表中搜索模式

提前感谢!

解决此问题的一种方法是将其重组为列表字典。类似的东西

list_of_dicts = [{"name": "thisisname1", "filebytestotal": 334632,"memorybytes": 5467234},    
{"name": "thisisname2", "filebytestotal": 2351, "memorybytes": 324523},    
{"name": "thisisname3", "filebytestotal": 2314651, "memorybytes": 2235},    
{"name": "thisisname1", "filebytestotal": 13432, "memorybytes": 546534},    
{"name": "thisisname1", "filebytestotal": 32342, "memorybytes": 341234}]
# reshape
from collections import defaultdict
dict_of_lists = defaultdict(list)
for obj in list_of_dicts:
dict_of_lists[obj['name']].append({
'bytestotal': obj['filebytestotal'],
'memorybytes': obj['memorybytes'],
})
dict_of_lists
> {'thisisname1': [{'bytestotal': 334632, 'memorybytes': 5467234}, ...], ...}
# and now calculate your averages
for key, totals_list in dict_of_lists.items():
bytes_total = [obj['bytestotal'] for obj in totals_list]
bytes_total_avg = sum(bytes_total) / len(bytes_total)
print(key, bytes_total_avg)
# and the same for memory bytes

这使用defaultdict,它用默认值填充任何空键。你可以用内置的字典来写,但这样可以节省几行。

这是一个带有"memorybytes"键的示例。

dic = [{"name": "thisisname1", "filebytes": 334632,"memorybytes": 5467234},{"name": "thisisname2", "filebytestotal": 2351, "memorybytes": 324523},{"name": "thisisname3", "filebytestotal": 2314651, "memorybytes": 2235},{"name": "thisisname1", "filebytestotal": 13432, "memorybytes": 546534},{"name": "thisisname1", "filebytestotal": 32342, "memorybytes": 341234}]
pattern_name = "1"
all_memorybytes = [element['memorybytes'] for element in dic if pattern_name in element['name'] ]
avg_memorybytes = sum(all_memorybytes) / float(len(all_memorybytes))
print avg_memorybytes

使用filebytestotal会出现问题,因为您有两个不同的密钥:"filebytes"one_answers"filebytestotal"。如果你在数组的所有元素中都有这个键,那么你可以通过更改理解列表中的键来使用相同的功能。

最新更新