mdandr
mdandr

Reputation: 1384

Simultaneously add key and + 1 value to dictionary in Python

Can I simultaneously add a key to a dictionary and assign a key + 1 value to the key?

My original script in the interpreter looked something like this:

>>> if isinstance('my current string', basestring):
...     mydictionary[mynewkey] = mydictionary[mynewkey] + 1

The error I get looks like this:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'mynewkey' is not defined

So I want to add mynewkey and a new value of 1 to mydictionary and ultimately be able to print mydictionary and come up with {mynewkey: 1}.

Upvotes: 1

Views: 291

Answers (2)

Irshad Bhat
Irshad Bhat

Reputation: 8709

At every occurrence of a newkey you need to initialize it first to some default value usually zero. After that you can increment it without any error message. Demo is shown below:

>>> a=['a','b','c','a','a','c']
>>> for mynewkey in a:
...     d.setdefault(mynewkey,0)
...     d[mynewkey]=d[mynewkey]+1
... 
>>> d
{'a': 3, 'c': 2, 'b': 1}

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123620

One way is to use dict.get():

mydictionary[mynewkey] = mydictionary.get(mynewkey, 0) + 1

Here mydictionary.get(mynewkey, 0) will return the value for the key named in mynewkey, or return 0 if no such key is present.

The easiest way is to use a collections.defaultdict() object, with int as the factory:

from collections import defaultdict

mydictionary = defaultdict(int)

Any key you try to access that doesn't exist yet is then initialised to 0, and you can simply do:

if isinstance('my current string', basestring):
    mydictionary[mynewkey] += 1

and it'll Just Work™

Upvotes: 7

Related Questions