Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find specific keys using specific values in python

I have 2 lists that contain months and total sales in that month and then I combined them into a dictionary. But I have a problem when trying to find which month have sales higher than average total sales. The code that I wrote just shows all months. Here is the code that I wrote:

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
total_sales = [1500,2250,1850,2000,2500,2400,2000,2100,2200,2800,2000,2750]

print('\n')

sales_per_month = dict(zip(months, total_sales))
print(sales_per_month)

print('\n')

average_sales = sum(sales_per_month.values())/len(sales_per_month.values())
print(average_sales)

print('\n')

for sales in sales_per_month.values():
  if sales > average_sales:
    print(sales_per_month.keys())
  else:
    pass

I have feeling that I was wrong when I wrote the looping part, but maybe I also did something wrong in other parts.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I fixed it for you:

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
total_sales = [1500,2250,1850,2000,2500,2400,2000,2100,2200,2800,2000,2750]

print('\n')

sales_per_month = dict(zip(months, total_sales))
print(sales_per_month)

print('\n')

average_sales = sum(sales_per_month.values())/len(sales_per_month.values())
print(average_sales)

print('\n')
for month, sales in sales_per_month.items():
    if sales > average_sales:
        print(month, sales)
    else:
        continue

output:

Feb 2250
May 2500
Jun 2400
Sep 2200
Oct 2800
Dec 2750
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading