r/Python • u/AlSweigart Author of "Automate the Boring Stuff" • Jun 05 '19
Pythonic Ways to Use Dictionaries
https://inventwithpython.com/blog/2019/06/05/pythonic-ways-to-use-dictionaries/6
u/FoeHammer99099 Jun 06 '19
It only comes up occasionally, but remember that the default argument to setdefault will always be evaluated, even if it doesn't end up being used. In scenarios where you don't want that, use defaultdict instead. (I almost never use setdefault these days because I prefer defaultdict for consistency/readability reasons)
5
u/masklinn Jun 06 '19
Also for this specific case
collections.Counter()is probably what you want if you're accumulating integrals.
1
u/Tweak_Imp Jun 07 '19
Is the dictionary as a switch replacement faster than the "if elif elif else" block?
1
u/AlSweigart Author of "Automate the Boring Stuff" Jun 07 '19
The only way to find out is to run it under a profiler. But even then, this is the sort of "clever trick"/micro-optimization that won't give a big enough benefit to justify writing less-readable code. The dictionary-as-switch is nice specifically for replacing single assignments. I wouldn't try to stretch it much past that.
Also, as others have pointed out, don't put function calls in the dictionary:
{'value1': doThing1(), 'value2': doThing2()}[someVariable]When the dictionary gets created, all the values are evaluated, meaning all of the functions are called no matter what
someVariableis set to.
1
3
u/caffeinepills Jun 05 '19
It definitely is much cleaner to use
dict.get. However, keep in mind if you are trying to optimize performance, it's 3-4x slower thanif key in dict.