-4

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.

A OH
  • 3
  • 3
  • Have you tried looping over the keys in one dictionary, getting the list and the multiplier with the same key from both dictionaries, multiplying them, and writing the results to the third dictionary? – mkrieger1 May 17 '21 at 13:06
  • @mkrieger1 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.. – A OH May 17 '21 at 14:10
  • So your actual question is how to multiply each value in a list by a factor. Luckily, this has already been asked and answered before: https://stackoverflow.com/questions/26446338/how-to-multiply-all-integers-inside-list – mkrieger1 May 17 '21 at 14:24
  • @mkrieger1 Thanks, I have already checked that before posting - it only deals with a single factor. When I try to use those solutions with the with the dictionary values as the factor, I get TypeError: can't multiply sequence by non-int of type 'dict_values'. – A OH May 17 '21 at 14:46
  • def magic(multipliers, lists): return {k: list(map(lambda x: m * x, lists[k])) for k, m in multipliers.items()} – jpsecher May 18 '21 at 18:31

1 Answers1

0

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
Dharman
  • 30,962
  • 25
  • 85
  • 135
samology
  • 161
  • 6