Python Forum
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
None in a dictionary
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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'
Reply
#3
so basically you are suggesting a special case string with a specific value, such as 'Not in dict' in this case.  i like it.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020