3

So I have a P = dict(). I have the following code:

def someFunction():
    P['key'] += 1
    '''do other task'''

What is the simplest way to check if P['key'] is defined or not?

I checked How do I check if a variable exists? but I am not sure if that answers my question.

Community
  • 1
  • 1
KKa
  • 408
  • 4
  • 19

3 Answers3

3

Two main ways to check in an ordinary dict:

The "look before you leap" paradigm. The else statement isn't required, of course, unless you want to define some alternate behavior:

if 'key' in P:
    P['key'] += 1
else:
    pass

The "easier to ask for forgiveness than permission" paradigm:

try:
    P['key'] += 1
except KeyError:
    pass  # Or do something else

Or you could use a defaultdict as suggested.

jayelm
  • 7,236
  • 5
  • 43
  • 61
1

You should use a defaultdict from the collections module.

from collections import defaultdict

d = defaultdict(int)
d[0] = 5
d[1] = 10

for i in range(3):
    d[i] += 1

# Note that d[2] was not set before the loop

for k, v in d.items():
    print('%i: %i' % (k,v))

prints:

brunsgaard@archbook /tmp> python test.py
0: 6
1: 11
2: 1
brunsgaard
  • 5,066
  • 2
  • 16
  • 15
  • This of course assumes that the reason the OP wants to check for `'key' in P` is to decide if he should be using `+= 1` or `= 1` :) – dano Oct 08 '14 at 01:44
  • @dano, not really. You would just modify you constructor to the defaultdict like so `defaultdict(lambda: 1)`. – brunsgaard Oct 08 '14 at 01:49
  • 1
    @brunsgaard it does assume that OP wants to initialize the value if it doesn't exist, rather than just skipping it (or doing something else). – jayelm Oct 08 '14 at 01:51
  • @JesseMu Right, that's what I was getting at. – dano Oct 08 '14 at 01:52
0

Usually I will check key presence with

if some_key in some_dict:
    print("do something")

Advanced usage: If you have a dictionary, key is string, value is a list. When key exists, you want to add an element to key associated value list. So you can

some_dict[some_key] = some_dict.get(some_key, []) + [new_item];
stanleyxu2005
  • 8,081
  • 14
  • 59
  • 94