Search code examples
pythondictionarylist-comprehension

List comprehension with different depth dictionaries


I have two dictionaries with the following structure:

  1. Quantity[week][day][time]
  2. Cost[day][time]

The goal is to multiply over a list comprehension the quantity * cost and then sum it. The Cost is the same for all weeks, however, the quantity will vary from week to week. Before adding the week to the first dictionary I had the following:

sum([Cost[day][time]*Quantity[day][time] for day,time in zip(df,tf)])

And it works as intended.
Is there a way to achieve the same with list comprehension now that the Quantity dictionary has one more level?

Edit

I want to have a different result for each week. It should be
sum(week1)+sum(week2)+...+sum(weekn)


Solution

  • Just add a week variable like so:

    [sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]
    

    Here is an example with an output:

    q = {'week1': {'day1': {'time1': 21, 
                            'time2': 30}, 
                   'day2': {'time1': 21, 
                            'time2': 40}}, 
         'week2': {'day1': {'time1': 22, 
                            'time2': 9}, 
                   'day2': {'time1': 23, 
                            'time2': 24}}}
    
    cost = {'day1': {'time1': 21, 
                    'time2': 24}, 
            'day2': {'time1': 22, 
                     'time2': 23}}
    
    wf = ['week1', 'week2']
    df = ['day1', 'day2']
    tf = ['time1', 'time2']
    
    output = [sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]
    
    print(output)
    

    Output:

    [1361, 1014]
    

    The output is a list of the sum for each week so the 'week1' sum is 1361 and the 'week2' sum is 1014.