Search code examples
pythonpython-3.xpython-2.7dictionarydictionary-comprehension

dictionary in python sum prices with 2 inputs


I have 2 inputs:

# The key is the available dates and the value is the price
a = {"g": 109192, "e": 116374, "o": 183368, "s": 162719}

# The dates that the user wants to take, this is going to be input by the user separeted by a space
b = ("g", "n", "e", "k", "s")

The program has to tell the user total cost of the dates and which one is available.

Output:

388285
g e s

My code so far:

import json
a=input("")
b=list(input().split(' '))
dic=json.dumps(a)
def citas(dic,b):
  citas_disponibles=[]
  suma=0
  for dia in b:
    if dia in a:
      suma += a[dia]
      citas_disponibles.append(dia)
  return citas_disponibles
citas(dic,b)

but the "suma" generate an "error"


Solution

  • def give_date_pricesum(a,b):
        #assuming b is a list
        available_dates = []
        sum = 0
        for date in b:
            try:
                sum = sum + a[date]
                available_dates.append(date)
            except:
                print("date is not available")
        return sum,available_dates
    

    So basically in the code, I have looped through the list of dates the user wants and checking them against our dictionary of prices. Whenever a date wanted is present, we are adding it to the sum and finally returning the sum and the available dates.
    If you want to run it for multiple users and want to update the dictionary, then you would want to delete the entries which get selected from the user's choice. For that, you can use del dictionary[key] format.