Federico De Marco
Federico De Marco

Reputation: 341

Multiplication between two different dictionary

I am trying to get a multiplication between two dictionary:

quantita_materiale={'140cm* 2cm': [1.0]}
prezzo_materiale={'140cm* 2cm': [100.0], '70cm* 2cm': [100.0],}

I want to get a result variable as a multiplication for all keys that matches between the two dictionaries.

I have tried to get the following code:

result={k : v * prezzo_materiale[k] for k, v in quantita_materiale.items() if k in prezzo_materiale}

But python gives me the following error:

can't multiply sequence by non-int of type 'list'

Upvotes: 2

Views: 59

Answers (2)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You were trying with a string with a list. That would definitely give a runtime error. You should instead be doing it as follows -

quantita_materiale={'140cm* 2cm': [1.0]}
prezzo_materiale={'140cm* 2cm': [100.0], '70cm* 2cm': [100.0],}

result={k : v[0] * int(prezzo_materiale[k][0]) for k, v in quantita_materiale.items() if k in prezzo_materiale}

print(result)
print("total - ",total)

Output :

{'140cm* 2cm': 100.0}
total - 100.0

The above method would only work if your values has only 1 element in the list. However, if you want it to work for values with lists having multiple elements, then you can use the following code -

quantita_materiale={'140cm* 2cm': [1.0,2.0]}
prezzo_materiale={'140cm* 2cm': [100.0,200.0], '70cm* 2cm': [100.0],}

result ={}
for k in quantita_materiale.keys():
    if k in prezzo_materiale:
        result[k] = [v1*v2 for v1,v2 in zip(quantita_materiale[k],prezzo_materiale[k])]
        
print(result)
total = sum(sum(result.values(),[]))
print("total",total)

Output :

{'140cm* 2cm': [100.0, 400.0]}
total 500.0

DO NOTE:

The first version of the answer won't work if the input has any value for a key that has more than one element in the list. So, the 2nd version of my answer would work for following inputs as well -

INPUT :

quantita_materiale={'140cm* 2cm': [1.0,2.0],'70cm* 2cm':[5.0]}
prezzo_materiale={'140cm* 2cm': [100.0,200.0], '70cm* 2cm': [100.0]}

OUTPUT :

{'140cm* 2cm': [100.0, 400.0], '70cm* 2cm': [500.0]}
total 1000.0 

Upvotes: 1

Andrey Maslov
Andrey Maslov

Reputation: 1466

result={k : v[0] * prezzo_materiale[k][0] for k, v in quantita_materiale.items() if k in prezzo_materiale}

when you try to get k, v for quantita_materiale.items(), you get k is str key, and v is a list containing 1 number, so if you want to get access to number you need to get first item of list that is v[0], the same is for prezzo_materiale[k]

this will give you a

result = {
 '140cm* 2cm': 100.0
}

if you want to have same result (list of integer)? you need to use this code:

    result={
        k : [v[0] * prezzo_materiale[k][0]] for k, v in quantita_materiale.items()  if k in prezzo_materiale
    }

it will returns

result = {
 '140cm* 2cm': [100.0]
}

Upvotes: 1

Related Questions