Home > database >  How to find a total year sales from a dictionary?
How to find a total year sales from a dictionary?

Time:11-20

I have this dictionary, and when I code for it, I only have the answer for June, May, September. How would I code for the months that are not given in the dictionary? Obviously, I have zero for them.

{'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'}

The method I used for months mentioned in the dictionary:

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

CodePudding user response:

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

CodePudding user response:

This might help:

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

Also, given the comments you have written, is this what you are looking for?

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)

{'January': 6, 'February': 0, 'March': 5, 'April': 5, 'May': 0, 'June': 0, 'July': 0, 'August': 0, 'September': 0, 'October': 0, 'November': 0, 'December': 0}

CodePudding user response:

You can read the following blog regarding the usage of dictionaries and how to perform calculations.

5 best ways to sum dictionary values in python

This is on of the examples given in the blog.

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))

Here is the result with 100,000 records.

Result with 100,000 records

  • Related