Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 454
Phillip Avatar asked Oct 01 '17 04:10

Phillip


People also ask

What is the difference between dict or dict get?

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.

What is get () in Python?

The get() method returns the value of the item with the specified key.

What is 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.

Is dictionary lookup faster than list Python?

Analysis Of The Test Run ResultA dictionary is 6.6 times faster than a list when we lookup in 100 items.


1 Answers

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.

like image 169
Code-Apprentice Avatar answered Oct 06 '22 00:10

Code-Apprentice