Python Forum
How would i go about adding up numbers in a dict
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How would i go about adding up numbers in a dict
#1
how would i add up the cost in this dict
foodstest = {'Dempsters Whole Wheat Bread': {"cost":2.27, "servings":18, "calories":1620},
             "Dempsters White Bread": {"cost":2.27, "servings":18, "calories":1620},
             "Dempsters Everything Bagels":{"cost":2.98, "servings":12, "calories":1200}}
Reply
#2
you need to iterate over items in foodtest and for each item, retrieve cost and sum.
as one-liner
total_cost = sum([value['cost'] for value in foodstest.values()])
print(total_cost)
in slow-motion
total_cost = 0
for value in foodstest.values():
    total_cost += value['cost']
print(total_cost)
to avoid getting KeyError if cost is missing, you can replace
value['cost'] with value.get('cost', 0)
Reply
#3
Ok thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  adding numbers in a list Nickd12 2 2,239 Jan-15-2021, 12:46 PM
Last Post: Serafim
  Adding markers to Folium map only adding last element. tantony 0 2,178 Oct-16-2019, 03:28 PM
Last Post: tantony
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,817 May-09-2019, 12:19 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020