Python Forum
Need help comparing totals from list of dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help comparing totals from list of dictionaries
#1
I need to write a code that will multiply the price of each item with its respective quantity and then return whichever dictionary has the highest total. In this case, Chocolate should be returned since it has the highest total (.75 * 9 = 6.75).

shopping_cart = {
"tax": .08,
"items": [
    {
        "title": "orange juice",
        "price": 3.99,
        "quantity": 1
    },
    {
        "title": "rice",
        "price": 1.99,
        "quantity": 3
    },
    {
        "title": "beans",
        "price": 0.99,
        "quantity": 3
    },
    {
        "title": "chili sauce",
        "price": 2.99,
        "quantity": 1
    },
    {
        "title": "chocolate",
        "price": 0.75,
        "quantity": 9
    }
]}
I believe I need to create an empty dictionary and use it to compare each item but I'm not sure. I've written the code below but I've hit a wall now. Any guidance would be appreciated.

def most_spent_on_item(d):
NewDict="title": " ",
"price": 0,
"quantity": 0
for i in d['items']:
i['price'] * i['quantity']
Reply
#2
Figured it out in case anyone ever needs to know.

def most_spent_on_item(d):
    
    NewDict={"title": "0 ",
    "price": 0,
    "quantity": 0}

    RunningHighestTotal=0
    
    for i in d['items']:
      if (i['price'] * i['quantity']) > RunningHighestTotal:
        RunningHighestTotal = (i['price'] * i['quantity'])
        NewDict['title']  =  i["title"]
        NewDict['price']  =  i["price"]
        NewDict['quantity']  =  i["quantity"]

    return NewDict
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionaries and list as values Pippi 6 3,592 Apr-13-2019, 09:05 AM
Last Post: perfringo
  Populating a list with Dictionaries.... SteenRudberg 4 2,759 Sep-26-2018, 11:09 AM
Last Post: SteenRudberg
  Newbie to Python - Problem in accessing Dictionaries and List sambill 1 3,105 Aug-17-2017, 07:38 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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