如何从字典中查找年度总销售额?



我有这本字典,当我为它编码时,我只有6月、5月和9月的答案。我该如何为字典中没有给出的月份编写代码?显然,我没有他们。

{'account': 'Amazon', 'amount': 300, 'day': 3, 'month': 'June'}
{'account': 'Facebook', 'amount': 550, 'day': 5, 'month': 'May'}
{'account': 'Google', 'amount': -200, 'day': 21, 'month': 'June'}
{'account': 'Amazon', 'amount': -300, 'day': 12, 'month': 'June'}
{'account': 'Facebook', 'amount': 130, 'day': 7, 'month': 'September'}
{'account': 'Google', 'amount': 250, 'day': 27, 'month': 'September'}
{'account': 'Amazon', 'amount': 200, 'day': 5, 'month': 'May'}

我用了几个月的方法在字典中提到:

year_balance=sum(d["amount"] for d in my_dict) print(f"The total year balance is {year_balance} $.")

import calendar
months = calendar.month_name[1:]
results = dict(zip(months, [0]*len(months)))
for d in data:
results[d["month"]] += d["amount"]
# then you have results dict with monthly amounts
# sum everything to get yearly total
total = sum(results.values())

这可能有帮助:

from collections import defaultdict
mydict = defaultdict(lambda: 0)
print(mydict["January"])

另外,考虑到你写的评论,这是你想要的吗?

your_list_of_dicts = [
{"January": 3, "March": 5},
{"January": 3, "April": 5}
]
import calendar
months = calendar.month_name[1:]
month_totals = dict()
for month in months:
month_totals[month] = 0
for d in your_list_of_dicts:
month_totals[month] += d[month] if month in d else 0
print(month_totals)

{' 1 ': 6个,"2":0,"3":5,"四月":5,"可能":0,"6月":0,"7":0,"八月":0,"九月":0,"十月":0,"11":0,"12":0}

你可以阅读下面的博客,了解字典的用法和如何进行计算。

用python对字典值求和的5种最佳方法

这是博客中给出的例子之一。

wages = {'01': 910.56, '02': 1298.68, '03': 1433.99, '04': 1050.14, '05': 877.67}
total = sum(wages.values())
print('Total Wages: ${0:,.2f}'.format(total))

这是100,000条记录的结果。

100,000条记录的结果

相关内容

  • 没有找到相关文章

最新更新