Function executes either the key is there or not in dictionary.get in python 2.7

Viewed 163

I am working with dictionaries in Python and I am searching for a value using:

my_dictionary_object.get("key")

As we all know if the key is missing in dictionary, it will return None object. So to save extra line and to make my code more interesting I am trying:

def my_function():
    '''do some calculations'''
    return missing_value_from_dictionary 

Now here is the fun part; when I do

my_dictionary_object.get("key", my_function())

it executes the function whether the key is missing or not so I thought let's remove the brackets and I did:

my_dictionary_object.get("key", my_function)

and (just in case)

my_dictionary_object.get("key", lambda: my_function())

but the one without lambda didn't execute (because it was never called) same happened with the one with lambda.

TL;DR

My question is why is the function get executed if the key is present in the dictionary?

Is it something that I am doing wrong or something I am missing here?

1 Answers

In: my_dictionary_object.get("key", my_function()) the execution looks something like:

  • Evaluate the first argument ("key")
  • Evaluate the second argument which is an expression: my_function(). So let's call the function, and use the return value in its place. Very much like in: a = my_function(), python would call the function and put the returned value in its place.
  • Call the mydictionary_object.get(..) with the above two evaluated arguments.

In other words, dictionary.get("key", default) will simply return the 2nd argument if the key doesn't exist. If it is a lambda, lambda is returned. A lambda is an object. Note that in .get("key", my_function()), my_function() is not technically the second argument. The resultant value returned as a result of execution of that function is the second argument -- which explains where you're wrong, hopefully.


What you are looking for is actually captured in another container called defaultdict.

What you'd do is:

from collections import defaultdict

my_dictionary_object = defaultdict(my_function)  # my_function should not take any argument.
my_dictionary_object["non-existing-key"]         # Magic happens, see below.

What happens is, if the key (=x) doesn't exist, my_function is called without any arguments and the dictionary is updated with the value returned by the function against the key (=x). Something like:

if "key" not in dictionary:
    dictionary["key"] = my_function()
    return dictionary["key"]
Related