Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment value of integer in Python dictionary

So I write an app that counts amount of yellow cards in football matches through all the games of the tournament. So let's say I count all Brazil's goals and I need to increment the amount of yellow cards with each game I go through in a loop. So I have this dictionary cards_per_team_dictionary that looks like this:

['Brazil', 0]

and I wan't to increment the int value with each game. I tried the following but it doesn't seem to work:

def add_yellow_cards_per_team(team_name, cards_num):
    cards_per_team_dictionary[team_name] += cards_num

I get an error:

cards_per_team_dictionary[team_name] += cards_num TypeError: 'set' object is not subscriptable 

And also this:

def add_yellow_cards_per_team(team_name, cards_num):
    cards_per_team_dictionary[team_name] + cards_num

But it seems to overrun the previous integer instead of adding up to it. Thanks in advance!

like image 936
Pavel Zagalsky Avatar asked Feb 07 '26 05:02

Pavel Zagalsky


1 Answers

You have created a set not a dict:

In [4]: d = {"Brazil",0}

In [5]: d["Brazil"] += 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-8db3ec29e78a> in <module>()
----> 1 d["Brazil"] += 3

TypeError: 'set' object is not subscriptable

To create a dict, you add key/value pairs separated by a colon i.e key:value:

In [6]: d = {"Brazil":0}

In [7]: d["Brazil"] += 3

In [8]: d
Out[8]: {'Brazil': 3}

Both a dict and set literals use {}, one difference being d = {} creates an empty dict where st = set() is needed to create an empty set.

If you want to add a key value pairing:

 d[key] = value

But for repeating keys you can use dict.setdefault:

data = [("Brazil", 4),("Argentina",6)]
d = {}
for team, count in data:
    d.setdefault(team, 0)
    d[team] += count

A more efficient option is to use a defauldict:

from collections import defaultdict
d = defaultdict(int)
for team, count in data:
    d[team] += count

In both cases if the key does not exist it is added with the new value, if it does exist the value for the key is increased.

like image 152
Padraic Cunningham Avatar answered Feb 09 '26 00:02

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!