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.
Python Dictionary get() Method The get() method returns the value of the item with the specified key.
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.
Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.
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.
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
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.
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