Get() function

I’m having trouble interpreting someone elses code.

hm = {}

if hm.get(0, 0) >= 3:

Isn’t this a useless if statement because the get function will always return 0? In essence, 0 is never greater than or equal to 3. Or does the get function not return zero every time?

dict.get(key) returns the value at key. It will return None in the above case.

>>> hm = {}
>>> hm.get('key') or 'None'

Based on the code that’s provided I can’t think of any way this would be useful and you’re quite right to query it.
The get method takes two arguments (key, value) and returns value if the key is not found. With just the code provided above this should only ever return the value, which is defined in the code as 0. The if statement will only ever provided false in this case (if 0 >= 3)

The default parameter of dict.get() would rightly be a value that would not be expected in the dictionary. We would want the return to be a useful signal.

>>> hm[0] = 0
>>> hm.get(0, 0)

Does that tell us anything definitive? Is there a useful signal, such that we can tell if the key exists?

>>> hm.get(0, None)

Now we can tell that the key does exist, and it is set to zero.

>>> hm.get(1)

No echoed response means None is returned.

you wouldn’t use that to determine whether it’s there
you would use that to get a default

As in an arbitrary value to use in further computation so there is no interruption?

It’s obviously always going to return zero, there’s nothing that would make it produce a different value each time you run that code, you are not for example using a random number generator. If everything is static, then the value you get the first time is the value you will get every time.
Presumably, that’s not the code they used.

Given the syntax if hm.get(0, 0) >= 3, what would have to be in the dictionary hm = {} for the if condition be met?

Or id the statement already a non starter?

what does dict.get do?
you could figure out how to get other results if you know what it does. right?

It gets or assigns a value to the key you put into it. That’s why I think the syntax doesn’t work. It should look likeif hm.get(0) >= 3 instead

go read what it says it does

1 Like

OK so the second position is what returns if the key is not found… Neat

Does that mean you did not know this when you opened the topic? Hard to believe the solution to your question was being told to read the documentation, but that’s how it appears. Maybe that’s the answer we should all adopt.

I’d assume if you were using the .get() method rather than simply testing if the given key exists in a particular dictionary using “in” you were then doing something with the output. In that case altering the default return from None can be useful. Perhaps not useful in the code originally posted but just using the default is limiting in may cases.