I have a list:
print(piezas_vendidos)
["['Queso']", "['Queso', 'Queso']", "['Queso', 'Queso']", "['Queso', 'Queso']", "['Queso']", "['Leche', 'Leche', 'Queso']", "['Queso', 'Queso']", "['Queso', 'Queso']", "['Queso', 'Queso']", "['Queso']", "['Queso', 'Queso', 'Queso']"]
I would like to get from this list a list like this: {'Cheese':19,'Milk':2}
How could it be done?
Each item in your list is actually another list, only it's stored as a string (for example
"['Queso']"
, instead of just['Queso']
.I would tell you to check how you generate those sub-lists to avoid putting them as strings, and have them as proper lists. If you solve that problem, that is, if your list
piezas_vendidas
contained:Then it would be enough to go through that list and then go through each of the sublists and gradually increase a dictionary in which the keys would be the items. For the latter, it is very convenient to use a
defaultdic()
because this way the elements that appear for the first time are created automatically without having to assign them a zero "manually".With this approach:
Result:
{'Queso': 19, 'Leche': 2}
Now, as you have it (each element being
piezas_vendidas
a string) it can also be solved by evaluating that string, to get the sublist in it. This solution would be very similar to the previous one, only addingeval()
in each sublist:However, the first solution is preferable, as it
eval()
can fail if any of the sublists contains something that is not interpretable by python. It can even become dangerous if any element of it ispiezas_vendidas
malicious python code.