Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionaries and default values

Assuming connectionDetails is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?

if "host" in connectionDetails:
    host = connectionDetails["host"]
else:
    host = someDefaultValue
like image 849
mnowotka Avatar asked Oct 08 '22 08:10

mnowotka


People also ask

Can you set a default value for dictionary Python?

Python dictionary setdefault() Method Python dictionary method setdefault() is similar to get(), but will set dict[key]=default if key is not already in dict.

What is a default dictionary?

Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError.

How does a default dictionary works?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.


3 Answers

Like this:

host = connectionDetails.get('host', someDefaultValue)
like image 414
MattH Avatar answered Oct 20 '22 23:10

MattH


You can also use the defaultdict like so:

from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"

You can pass any ordinary function instead of lambda:

from collections import defaultdict
def a():
  return 4

b = defaultdict(a, key="some_value")
b['absent'] => 4
b['key'] => "some_value"
like image 133
tamerlaha Avatar answered Oct 20 '22 23:10

tamerlaha


While .get() is a nice idiom, it's slower than if/else (and slower than try/except if presence of the key in the dictionary can be expected most of the time):

>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10")
0.07691968797894333
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="try:\n a=d[2]\nexcept KeyError:\n a=10")
0.4583777282275605
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="a=d.get(1, 10)")
0.17784020746671558
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="a=d.get(2, 10)")
0.17952161730158878
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="if 1 in d:\n a=d[1]\nelse:\n a=10")
0.10071221458065338
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10")
0.06966537335119938
like image 32
Tim Pietzcker Avatar answered Oct 20 '22 23:10

Tim Pietzcker