python 如何从字典中找到一年的总销售额?

but5z9lq  于 2022-11-21  发布在  Python
关注(0)|答案(3)|浏览(166)

我有一本字典,当我为它编码的时候,我只有六月,五月,九月的答案。我该如何为字典中没有的月份编码呢?显然,我为它们编码为零。

{'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} $.")

9cbw7uwe

9cbw7uwe1#

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())
6rqinv9w

6rqinv9w2#

这可能有助于:

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)

{“一月”:6,“二月”:0,'三月':5,“四月”:5,“五月”:0,“六月”:0,“七月”:0,“八月”:0,'九月':0,'十月':0,“十一月”:0,'十二月':0个字符}

mbyulnm0

mbyulnm03#

您可以阅读以下博客,了解字典的用法以及如何执行计算。
5 best ways to sum dictionary values in python
这是博客中给出的例子之一。

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条记录的结果。
Result with 100,000 records

相关问题