Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add or increment a dictionary entry?

Tags:

python

syntax

I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way.

The code that I'm writing is in the following form:

# foo is a dictionary if foo.has_key(bar):   foo[bar] += 1 else:   foo[bar] = 1 

I'm writing this a lot in my programs. My first reaction is to push it out to a helper function, but so often the python libraries supply things like this already.

Is there some simple little syntax trick that I'm missing? Or is this the way that it should be done?

like image 646
cursa Avatar asked Apr 12 '10 23:04

cursa


People also ask

How do you increment a dictionary?

By using the get() function we can increment a dictionary value and this method takes the key value as a parameter and it will check the condition if the key does not contain in the dictionary it will return the default value. If the given key exists in a dictionary then it will always return the value of the key.

How do you add an entry to a dictionary?

Appending element(s) to a dictionary To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.


1 Answers

The dict's get() method takes an optional second parameter that can be used to provide a default value if the requested key is not found:

foo[bar] = foo.get(bar, 0) + 1 
like image 161
sth Avatar answered Sep 26 '22 06:09

sth