D
Can you do it using https://www.tutorialspoint.com/python3/dictionary_setdefault.htm , and yes, it is not enough to use two cycles:t = [[1,2],[2,1],[3,1],[4,1],[1,1],[2,2],[1,2]]
dicionario = {}
for k, v in t: # unpacking dos valores de cada sublista
dicionario[k] = dicionario.setdefault(k, 0) + v
print(dicionario) # {1: 5, 2: 3, 3: 1, 4: 1}
setdefault, if there is no key in the dict, it will assign a value default (second argument) to the new key (first argument) inserted in the dict.In a slightly more noticeable/readable way:t = [[1,2],[2,1],[3,1],[4,1],[1,1],[2,2],[1,2]]
dicionario = {}
for k, v in t: # unpacking dos valores de cada sublista
if k not in dicionario:
dicionario[k] = 0
dicionario[k] += v
print(dicionario) # {1: 5, 2: 3, 3: 1, 4: 1}
As pointed out and well in comment, here with the use of http://www.tutorialspoint.com/python/dictionary_get.htm you would have the same final result, although it is a little slower the difference is irrisory in this case:t = [[1,2],[2,1],[3,1],[4,1],[1,1],[2,2],[1,2]]
dicionario = {}
for k, v in t: # unpacking dos valores de cada sublista
dicionario[k] = dicionario.get(k, 0) + v
print(dicionario) # {1: 5, 2: 3, 3: 1, 4: 1}
https://stackoverflow.com/questions/7423428/python-dict-get-vs-setdefault