Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create default values for dictionary in python

Let's have a method that would cache results it calculates.

"If" approach:

def calculate1(input_values):
    if input_values not in calculate1.cache.keys():
        # do some calculation
        result = input_values
        calculate1.cache[input_values] = result
    return calculate1.cache[input_values]
calculate1.cache = {}

"Except" approach:

def calculate2(input_values):
    try:
       return calculate2.cache[input_values]
    except AttributeError:
       calculate2.cache = {}
    except KeyError:
       pass
    # do some calculation
    result = input_values
    calculate2.cache[input_values] = result
    return result

"get/has" approach:

def calculate3(input_values):

    if not hasattr(calculate3, cache):
        calculate3.cache = {}

    result = calculate3.cache.get(input_values)
    if not result:
        # do some calculation
        result = input_values
        calculate3.cache[input_values] = result
    return result

Is there another (faster) way? Which one is most pythonic? Which one would you use?

Note: There's a speed difference:

calculate = calculateX # depening on test run
for i in xrange(10000):
    calculate(datetime.utcnow())

Results time python test.py:

calculate1: 0m9.579s
calculate2: 0m0.130s
calculate3: 0m0.095s
like image 287
Martin Tóth Avatar asked Dec 01 '10 15:12

Martin Tóth


People also ask

How do you create a default value in a dictionary?

Using fromkeys() function If you want to initialize all keys in the dictionary with some default value, you can use the fromkeys() function. If no default value is specified, the dictionary is initialized with all values as None .

What is the default value of dictionary in Python?

default defaults to None . Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError . In the above code, you use .

What does .setdefault do in Python?

Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary.

How do you initialize a dictionary in Python?

Another way to initialize a python dictionary is to use its built-in “dict()” function in the code. So, you have to declare a variable and assign it the “dict()” function as an input value. After this, the same print function is here to print out the initialized dictionary.


2 Answers

Use a collections.defaultdict. It's designed precisely for this purpose.

like image 112
unutbu Avatar answered Oct 01 '22 12:10

unutbu


Of course; this is Python after all: Just use a defaultdict.

like image 43
Aaron Digulla Avatar answered Oct 01 '22 10:10

Aaron Digulla