Dictionaries and default values
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
00:25 Accepted answer (Score 430)
00:38 Answer 2 (Score 137)
01:01 Answer 3 (Score 32)
01:35 Answer 4 (Score 21)
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/9358...
Answer 1 links:
[defaultdict]: https://docs.python.org/2/library/collec...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #codingstyle
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Question
00:25 Accepted answer (Score 430)
00:38 Answer 2 (Score 137)
01:01 Answer 3 (Score 32)
01:35 Answer 4 (Score 21)
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/9358...
Answer 1 links:
[defaultdict]: https://docs.python.org/2/library/collec...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #codingstyle
#avk47
ACCEPTED ANSWER
Score 462
Like this:
host = connectionDetails.get('host', someDefaultValue)
ANSWER 2
Score 146
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"
ANSWER 3
Score 33
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
ANSWER 4
Score 22
For multiple different defaults try this:
connectionDetails = { "host": "www.example.com" }
defaults = { "host": "127.0.0.1", "port": 8080 }
completeDetails = {}
completeDetails.update(defaults)
completeDetails.update(connectionDetails)
completeDetails["host"] # ==> "www.example.com"
completeDetails["port"] # ==> 8080