Search code examples
pythonlistdictionaryintegermultiplication

How to multiply list by integer within dictionary?


example = {'good':[1,2],'bad':[5,10],'great':[9,4]}

example2 = {'good':2,'bad':3}

I want to multiply the list values by the integers for the matching keys and create a new dictionary, so I should get:

example3 = {'good':[2,4],'bad':[15,30]}

How can I do this? I have tried:

example3 = {k:example.get(k) * example2.get(k) for k in set(example) & set(example2)}

but the output is:{'bad': [5, 10, 5, 10, 5, 10], 'good': [1, 2, 1, 2]}

The problem I have is how to multiply the list values by integers.


Solution

  • Your code is duplicating every corresponding list (values) in example1 as many times as the values in example2.

    Your code is similar to:

    >>>>two_items = ["A","B"]
    >>>>number = [3]
    >>>>result = two_items*number[0]
    
    ['A', 'B', 'A', 'B', 'A', 'B']
    

    To make this clear, it works like string multiplication:

    >>>>my_string="Hello "
    >>>>print(my_string * number[0])
    Hello Hello Hello 
    

    What you need to do is to iterate through each items in the list and multiply it by a given number, as following:

    >>>>two_numbers=[1,2]
    >>>>number=[3]
    >>>>result=[]
    >>>>for num in two_numbers:
    >>>>    x =num * number[0]
    >>>>    result.append(x)
    [3, 6]
    

    Given the above, your code should look like that:

    example3 = {}
    for key in example2.keys():
        temp =[]
        for item in example[key]:   
            temp.append(item*example2[key])
        example3[key]=temp