Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dict: get() not returning 0 if dict value contains None

Tags:

python

python dict if a key having value None and when called get() returns NoneType

ex_dict = {"test" : None} ex_dict.get('test', 0)

In above example it should return 0 but it wont.

Can any explain why it behave like that.

like image 893
Manoj Jadhav Avatar asked Mar 15 '17 09:03

Manoj Jadhav


People also ask

Can you explain the dict get () function?

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

What does dictionary get return if key not found?

The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None.

What does Python dictionary get return if key not found?

Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.

Should I use dict () or {}?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


2 Answers

No, it shouldn't. If test key is not found in the ex_dict dictionary it should return 0. But, because it exists it will return None

ex_dict = {"test" : None}
print type(ex_dict.get('test', 0))  # <class 'NoneType'>, 'test' exist, return None

print(ex_dict.get('hello', 0))  # prints 0, 'hello' isn't a key inside ex_dict
like image 162
nik_m Avatar answered Sep 30 '22 16:09

nik_m


The None response in ex_dict.get('test', 0) is ok because the "test" key exists and has None value. For instance, if you try the same with ex_dict.get("non_existing_key", 0) it returns 0.

like image 29
Andruten Avatar answered Sep 30 '22 15:09

Andruten