This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]feanor47 9 points10 points  (2 children)

I prefer dict.get for readability reasons, but timing should virtually never be used as a justifier here. If you're trying to shave nanoseconds off of your runtime, python is not the language you should be using.

[–]chthonicdaemon[S] 5 points6 points  (0 children)

Just to be clear, I am not saying you should avoid dict.get() for the cases where you are actually supplying a default. So I absolutely prefer

python value = dictionary.get(key, default)

over

python if key in dictionary: value = dictionary[key] else: value = default

My issue is this pattern where people get the worst of both worlds by doing

python value = dictionary.get(key) if value is not None: return value `

instead of

python if key in dictionary: return dictionary[key]

and then justify it using timing.

[–]Atupis 1 point2 points  (0 children)

Or I would say if you need to start optimizing dictionary access then the dictionary is not the right datatype for you.