'None' returned from a call to '.get()' issue

Viewed 143

Getting a None returned from a call to .get() could mean that the key wasn't found or that the value found at the key in the dictionary is actually None.

So what can I set the return value to if nothing is found and interpreted has 0 in boolean test?

for write this:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
age = ages.get(person, ?) #what need to be '?'

if age:
    print(f'{person} is {age} years old.')
else:
    print(f"{person}'s age is unknown.")
3 Answers

You don't need to use .get. Just access the dictionary value directly.

Like this:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')

try:
    age = ages[person]
    
    if age:
        print(f'{person} is {age} years old.')
    else:
        print(f"{person}'s age is unknown.")
except KeyError:
    print(f"Unknown person: {person}")
    

In this case it would be useful to use try/except:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
try:
    age = ages[person] #what need to be '?'
    if age:
        print(f'{person} is {age} years old.')
    else:
        print(f"{person}'s age is unknown.")
except KeyError:
    print(f'{person} not found in ages')

output

Get age for: Jim
Jim is 30 years old.

Get age for: Kevin
Kevin's age is unknown.

Get age for: Bob
Bob not found in ages
ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')

try:
    age = ages[person]
    
    if age:
        print(f'{person} is {age} years old.')
    else:
        print(f"{person}'s age is unknown.")
except KeyError:
    print(f"{person} is not known.")
Related