Phillip Phillip - 3 years ago 189
Python Question

Python Dictionary: "in" vs "get"

I am a little confused between the use of "in" vs "get" when searching for an element within the dictionary.

According to this time complexity table, here: when using "in" we get O(n) vs "get" we get O(1).

In these two code snippets below, they achieve the same thing, but apparently using get will be much faster?

#Recall that for "get" the second parameter is returned if key is not found

#O(1) time complexity
if dict.get(key, False):
return "found item"

#O(n) time complexity
if key in dict:
return "found item"


I do not understand how using a get would change the time complexity when they can both achieve the same thing. Except the get call will actually return the value if its found.

Questions: How is it that "in" time complexity is O(n) while "get" is only O(1) when they both achieve the same results? Is there ever a reason to use "in" with dictionaries if this is true?

Answer Source

get() returns the value for the given key, if the key exists in the dict.

in returns a boolean value depending on if the value key is present in the dict.

Use get() if you need the value. Use in if you only need to test if the key exists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download