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?
get() is usually preferred, as it accepts a second argument which acts as the default value shall the key not exist in the given dictionary. Due to this property, dict. get() will always return a value, whereas dict[key] will raise a KeyError if the given key is missing.
The get() method returns the value of the item with the specified 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.
Analysis Of The Test Run ResultA dictionary is 6.6 times faster than a list when we lookup in 100 items.
get()
returns the value for the given key, if the key exists in the dict.
in
returns a boolean value depending on if the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With