用词典列表制作新词典

时间:2019-05-07 00:31:51

标签: python python-3.7

我有一个词典列表

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] 

这是正确的方法吗?或最佳方法是什么?

谢谢!

2 个答案:

答案 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