1
I need to create a dictionary from a list of integers, where each key contains the value of the sums that are in the list:
t = [[1,2],[2,1],[3,1],[4,1],[1,1],[2,2],[1,2]]
dicionario = {}
for i in t:
dicionario[str(i[0])] = 0
for i in t:
dicionario[str(i[0])] += i[1]
Where my dictionary would have the result: {'1':5,'2':3,'3':1,'4':1}
But I’m doing two loops as you can see, but how I need this task to be as fast as possible, that is, with only one loop as I would do it?
t = [[1,2],[2,1],[3,1],[4,1],[1,1],[2,2],[1,2]]
dicionario = {}
for i in t:
dicionario[str(i[0])] += i[1]
KeyError Traceback (most recent call last)
<ipython-input-8-8eda406a14d0> in <module>()
1 for i in t:
----> 2 dicionario[str(i[0])] += i[1]
3
KeyError: '1'
Taking advantage, could also put the option of
dicionario.get(k, default=0)
? Even though it has some particularities when compared tosetdefault
I believe that it is worth mentioning, even for the legibility of the code.– Woss
Obgado @Andersoncarloswoss, added this alternative
– Miguel