dictionaries - python get value from dictionary if key exists

Check if a given key already exists in a dictionary (13)

in is the intended way to test for the existence of a key in a dict.

d = dict()

for i in xrange(100):
    key = i % 10
    if key in d:
        d[key] += 1
        d[key] = 1

If you wanted a default, you can always use dict.get():

d = dict()

for i in xrange(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1

... and if you wanted to always ensure a default value for any key you can use defaultdict from the collections module, like so:

from collections import defaultdict

d = defaultdict(lambda: 0)

for i in xrange(100):
    d[i % 10] += 1

... but in general, the in keyword is the best way to do it.

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:

if 'key1' in dict.keys():
  print "blah"
  print "boo"

I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?

print dict.get('key1', 'blah')

Won't print boo for the values in the dict, but accomplishes the goal by printing the value of key1 to confirm it's existence instead.

You can use the has_key() method:

if dict.has_key('xyz')==1:
    #update the value for the key

Or the dict.get method to set a default value if not found:

mydict = {"a": 5}

print mydict["a"]            #prints 5
print mydict["b"]            #Throws KeyError: 'b'

print mydict.get("a", 0)     #prints 5
print mydict.get("b", 0)     #prints 0

Dictionary in python has a get('key', default) method. So you can just set a default value in case there is no key.

values = {...}
myValue = values.get('Key', None)

For additional info on speed execution of the accepted answer's proposed methods (10m loops):

  • 'key' in mydict elapsed time 1.07 sec
  • mydict.get('key') elapsed time 1.84 sec
  • mydefaultdict['key'] elapsed time 1.07 sec

Therefore using in or defaultdict are recommended against get.

For checking you can use has_key() method

if dict.has_key('key1'):
   print "it is there"

If you want a value then you can use get() method

a = dict.get('key1', expeced_type)

If you want a tuple or list or dictionary or any string as a default value as return value, then use get() method

a = dict.get('key1', {}).get('key2', [])

I would recommend using the setdefault method instead. It sounds like it will do everything you want.

>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}

Just an FYI adding to Chris. B (best answer):

d = defaultdict(int)

Works as well; the reason is that calling int() returns 0 which is what defaultdict does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.

Using ternary operator:

message = "blah" if 'key1' in dict else "booh"

Well.. You will be familiar that searching a element's existence in a list or data means going through everything (at least for unordered list e.g dict.keys ).So Instead using Exception and Errors that arise normally we can avoid that complexity...

    print("Key doesnt exist")

Why not just use the has_key() method.

a = {}
a.has_key('b') => #False

a['b'] = 8
a.has_key('b') => #True

You can shorten this:

if 'key1' in dict:

However, this is at best a cosmetic improvement. Why do you believe this is not the best way?

You don't have to call keys:

if 'key1' in dict:
  print "blah"
  print "boo"

That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.