Python Forum
None in a dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: None in a dictionary (/thread-3225.html)



None in a dictionary - Skaperen - May-07-2017

i have a case where i am getting a member from a dictionary and much later, elsewhere in the code with no access to the original dictionary, the code needs to determine if it was in the dictionary or not.  my first reaction was to code it up to set it to None if it was absent.  but i had an issue.  it was possible to have a None value in the dictionary.  the code needed to distinguish the case of key:None in the dictionary and having been given a default value because it was not in the dictionary.  i need to come up with a way to code a value to it that is different for the case of absent.  any ideas?


RE: None in a dictionary - snippsat - May-07-2017

If using get() you can set parameter so it do not return None(Default).
>>> d = {'Car': 5, 'foo': None}

>>> d.get('Car', 'Not in dict')
5
>>> repr(d.get('foo', 'Not in dict'))
'None'
>>> d.get('bar', 'Not in dict')
'Not in dict'
>>> d.get('aaaa', 'Not in dict')
'Not in dict'



RE: None in a dictionary - Skaperen - May-08-2017

so basically you are suggesting a special case string with a specific value, such as 'Not in dict' in this case.  i like it.