How to create a dictionary and auto increment values?

Asked

Viewed 1,071 times

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'

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 there is no key already in Dict, will assign a value default (second argument) to the new key (first argument) inserted in 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 get you would have the same end result, even though it’s a little slower the difference is laughable 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

  • Taking advantage, could also put the option of dicionario.get(k, default=0)? Even though it has some particularities when compared to setdefault I believe that it is worth mentioning, even for the legibility of the code.

  • Obgado @Andersoncarloswoss, added this alternative

Browser other questions tagged

You are not signed in. Login or sign up in order to post.