[英]Making a new dictionary out of a List of Dictionaries
I have a list of dictionaries : 我有一个词典列表 :
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}]
My goal is to find the product with the top total of sales : 我的目标是找到销售额最高的产品 :
Output = [Cereal, 28.82]
So far, I have been able to extract dictionaries to a list: 到目前为止,我已经能够将字典提取到列表中:
list = [['Cereal',12.99,'Cereal1',9.99,'Cereal2', 11.99,'Cereal', 15.83, 'Cereal1, 10.99,'Cereal2',9.99]
Is this a proper way? 这是一种正确的方法吗? or What is the best way to do it?
或者最好的方法是什么?
Thanks! 谢谢!
You can use collections.Counter
to accumulate the price
for each product
, then take the max
at the end: 您可以使用
collections.Counter
累积每个product
的price
,然后在最后获取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)
If you want the result to be a list
instead of tuple
: 如果您希望结果是
list
而不是tuple
:
print(list(max(counts.items(), key=itemgetter(1))))
# ['Cereal', 28.82]
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()
This will give you the sum as expect 这将为您提供预期的金额
Cereal 28.82 Cereal1 20.98 Cereal2 21.98 谷物28.82谷物1 20.98谷物2 21.98
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.