How to create a dictionary and auto increment values?

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 do I make this task as fast as possible, ie with just one loop how would I 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'
    
asked by anonymous 22.01.2018 / 15:46

1 answer

3

You can do it using setdefault , and yes, it is unnecessary 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 the key does not already exist in the dict, it will assign a default (second argument) value to the new one of the key (first argument) inserted in the dict.

In a slightly more perceptible / 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 well in commentary, here with the use of get would have the same end result , although it is a bit slower the difference is ridiculous 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}

get vs setdefault

    
22.01.2018 / 16:02