问题描述
result = {
"resultset": [
{"name": "DOG","threshold": Decimal("1.45600000"),"current_value": 124},{"name": "DOG","current_value": 14},"current_value": 1},{"name": "CAT","current_value": 24},"current_value": 4},]
}
现在我想实际做2件事,基本上是在我得到的地方做一个凝结:
- 当前值列表[]
- 阈值的平均值
所以最后我想看看:
{
'DOG': {'current_values': [124,14,1],'threshold': the average of threshold},'CAT': {'current_values': [24,4],'threshold': the average of threshold}
}
我可以使用其中的一半来获取current_values列表,但不能使用默认的dict来获取整个列表,
all_animals = defaultdict(list)
for i in result['resultset']:
all_animals[i['name']].append(float(i['current_value']))
有人可以帮我吗
解决方法
带有defaultdict
和statistics
的蛋糕:
from decimal import Decimal
from collections import defaultdict
import statistics
result = {
"resultset": [
{
"name": "DOG","threshold": Decimal("1.45600000"),"current_value": 124,},{
"name": "DOG","current_value": 14,"current_value": 1,{
"name": "CAT","current_value": 24,"current_value": 4,]
}
current_values_by_name = defaultdict(list)
thresholds_by_name = defaultdict(list)
for x in result["resultset"]:
current_values_by_name[x["name"]].append(x["current_value"])
thresholds_by_name[x["name"]].append(x["threshold"])
aggregate_result = {
name: {
"current_values": current_values_by_name[name],"threshold": statistics.mean(thresholds_by_name[name]),}
for name in current_values_by_name
}
print(aggregate_result)
输出
{
"DOG": {
"current_values": [124,14,1],"threshold": Decimal("1.456"),"CAT": {
"current_values": [24,4],}