Search code examples
pythondefaultdict

Writing code for dict and defaultdict


I have the following problem:

from collections import defaultdict

def give_it_to_me(d):
    # This will crash if key 'it' does not exist
    return d['it']

def give_it2_to_me(d):
    # This will never crash, but does not trigger the default value in defaultdict
    return d.get('it2')

d1 = defaultdict(int)
d2 = { 'it' : 55 }

print give_it_to_me(d1)
print give_it_to_me(d2)

print give_it2_to_me(d1)
print give_it2_to_me(d2)

As you can see in the comments, it seems impossible to write a version of give_it_to_me which:

  1. Does never crash
  2. Triggers the default value for defaultdicts

Or am I wrong?


Solution

  • You might need a bit more code in your give_it_to_me function.

    Use a try except statement to check for an existing key.

    For example:

    def give_it_to_me(d):
        # This won't crash if key 'it' does not exist in a normal dict.
        # It returns just None in that case.
        # It returns the default value of an defaultdict if the key is not found.
        try:
            return d['it']
        except KeyError:
            return None