A very concise way would be the following:
cortes=['raspall', 'garson', 'mao-tse', 'punki', 'kunki']
prop=[('mao-tse', 2), ('raspall', 5), ('raspall', 2), ('garson', 10),('mao-tse', 6), ('kunki', 3)]
from collections import defaultdict
d = defaultdict(int)
for k,v in prop:
if k in cortes:
d[k]+=v
print(list(d.items()))
[('mao-tse', 8), ('raspall', 7), ('garson', 10), ('kunki', 3)]
Explanation
I use a defaultdict
that is a python data type equivalent to the dictionary, but that does not give an error if you try to access a key that does not exist, but gives you a default value. The variable in question is d
. If we try to look at d['foobar']
, since that key does not exist, it gives me the default value, which is 0 because I specified when creating it that it was int
.
That allows me to accumulate (add) in that dictionary with an expression like d[k]+=v
, since if k
did not exist, it will assume the value 0, add v
and leave that result in the key k
, that from that moment will already exist.
With this trick it is enough to go through the list prop
, separating its tuples into two variables k
and v
( k
for the name, v
for the value), and see if k
is in cortes
to add the value.
Once we have finished, list(d.items())
converts the dictionary that stores the results in a list of tuples.
Update
The user asks how to do it without importing extra modules (although the collections
module is part of the standard python, you do not have to install anything extra, but good), but using only "normal" types and loops.
The code explained above can be trivially adapted to these requirements. Instead of defaultdict
we use a normal dictionary and simply put a 0 if the key did not exist previously:
d = {} # Diccionario inicialmente vacío
for k, v in prop:
if k in cortes:
if k not in d: # <--- esto es lo nuevo
d[k] = 0 # <----
d[k] += v
print(d)
{'mao-tse': 8, 'raspall': 7, 'garson': 10, 'kunki': 3}
In this case I print the result dictionary directly. If you want the list of tuples you would get as in the previous answer.
Note, however, that the keys that do not appear in prop
will not appear in the result either (such as punki
). If you want them to appear with zero counter, one option is to prepare the dictionary beforehand with zeros in all those keys:
d = {}
# Primero poner un 0 en todas las claves
for k in cortes:
d[k] = 0
# Ahora sumarles los valores que vayamos encontrando.
for k, v in prop:
if k in cortes:
d[k]+=v
print(d)
{'raspall': 7, 'garson': 10, 'mao-tse': 8, 'punki': 0, 'kunki': 3}
Notice that if in prop
appear a name not present in cortes
, this would not be part of the result, which I guess is what is requested.