我有一个词典列表:
dicti = [{**'product':** 'Cereal', 'price': 12.99},
{**'product'**: 'Cereal1', 'price': 9.99},
{**'product'**: 'Cereal2', 'price': 11.99},
{**'product'**: 'Cereal', 'price' : 15.83},
{**'product'**: 'Cereal1', 'price': 10.99},
{**'product'**: 'Cereal2', 'price': 9.99}]
我的目标是找到销量销售总额最高的产品:
Output = [Cereal, 28.82]
到目前为止,我已经能够将字典提取到列表中:
list = [['Cereal',12.99,'Cereal1',9.99,'Cereal2', 11.99,'Cereal', 15.83, 'Cereal1, 10.99,'Cereal2',9.99]
这是正确的方法吗?或最佳方法是什么?
谢谢!
答案 0 :(得分:0)
您可以使用collections.Counter
为每个price
累积product
,然后在末尾取max
:
from collections import Counter
from operator import itemgetter
dicti = [
{"product": "Cereal", "price": 12.99},
{"product": "Cereal1", "price": 9.99},
{"product": "Cereal2", "price": 11.99},
{"product": "Cereal", "price": 15.83},
{"product": "Cereal1", "price": 10.99},
{"product": "Cereal2", "price": 9.99},
]
counts = Counter()
for x in dicti:
counts[x["product"]] += x["price"]
print(max(counts.items(), key=itemgetter(1)))
# ('Cereal', 28.82)
如果您希望结果是list
而不是tuple
:
print(list(max(counts.items(), key=itemgetter(1))))
# ['Cereal', 28.82]
答案 1 :(得分:0)
import pandas as pd
dicti = [{'product': 'Cereal', 'price': 12.99},
{'product': 'Cereal1', 'price': 9.99},
{'product': 'Cereal2', 'price': 11.99},
{'product': 'Cereal', 'price' : 15.83},
{'product': 'Cereal1', 'price': 10.99},
{'product': 'Cereal2', 'price': 9.99}]
sd = pd.DataFrame.from_dict(dicti )
sd.groupby('product').sum()
这将给您期望的总和
谷物28.82 谷物1 20.98 谷物2 21.98