Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dict.get(key, default) vs dict.get(key) or default

Is there any difference (performance or otherwise) between the following two statements in Python?

v = my_dict.get(key, some_default)

vs

v = my_dict.get(key) or some_default
like image 676
Brad Johnson Avatar asked Oct 21 '15 15:10

Brad Johnson


People also ask

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

What is the difference between D key and D get key?

The main difference between these two methods is what happens when the given key does not exist in the dictionary. When given such a key, d[key] will cause an error, and d. get(key) will just return None, signifying that there is no value associated with that key.

How is the function get () different from the Setdefault () for dictionary class?

The get the method allows you to avoid getting a KeyError when the key doesn't exist however setdefault the method allows set default values when the key doesn't exist.

What is the difference between default dict and dict?

The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key . In order to provide this functionality, the Python defaultdict type does two things: It overrides .


1 Answers

There is a huge difference if your value is false-y:

>>> d = {'foo': 0}
>>> d.get('foo', 'bar')
0
>>> d.get('foo') or 'bar'
'bar'

You should not use or default if your values can be false-y.

On top of that, using or adds additional bytecode; a test and jump has to be performed. Just use dict.get(), there is no advantage to using or default here.

like image 141
Martijn Pieters Avatar answered Sep 25 '22 00:09

Martijn Pieters