Python 2.7.14: "+=1 to Dictionary Item if Key Exists Else = 1" Syntax Doesn't Work

Viewed 157

I'm trying to +=1 to an item in a dictionary if it exists, else create the key in the dictionary and set it to 1. I know I can use more than one line of logic for this, but I really want to see if its possible to keep the logic on one line. This is what I'm trying to do:

myDict = {}
myDict[100] += 1 if 100 in myDict else 1

It throw KeyError though if the key 100 doesn't exist. How can I set the one lined else logic to set key 100 to 1? Is it even possible?

Many thanks

5 Answers

The problem is that this is parsed as

myDict[100] += (1 if 100 in myDict else 1)

which is just the same as writing

myDict[100] += 1

and of course that requires myDict[100] already to exist. You can instead use a regular assignment and the dictionary get method, which lets you specify what is to be returned if the key is not already there:

myDict[100] = myDict.get(100, 0) + 1

Or you can use collections.Counter, which is a special-purpose dictionary designed for exactly this job:

import collections
myDict = collections.Counter()
myDict[100] += 1

Use get:

my_dict = {}
my_dict[100] =  my_dict.get(100, 0) +  1

Output

{100: 1}

Explanation (from the documentation)

Return the value for key if key is in the dictionary, else default

You are indexing already in the value so the error is thrown if is not in the dict This would work

if 100 in mydict:
    mydict[100] += 1
else:
    mydict[100] = 1

However even prettier would be mydict[100] = mydict.get(100, 0) + 1

In addition to collections.Counter there is collections.defaultdict, which allows you to set a default value to be used when a non-initialized key is passed to the dict. It is overkill for counters of course, but can be really wonderful in other situations.

myDict[100] = myDict[100]+1 if 100 in myDict else 1

or, maybe better:

myDict.setdefault(100, 0)
myDict[100] +=1
Related