-3

There is a dictionary object named my_dic.

my_dic = {'name': 'tom'}
print(f"The name is {my_dic.get('name')}")

In case my_dic is None, there will be an expected exception as 'NoneType' object has no attribute 'get'.

How to make one line code to get None in case my_dic is None, otherwise return by get().

Thanks.

2 Answers2

1

You might use a conditional expression to handle the case where my_dic is None.

>>> my_dic = None
>>> print(f"The name is {my_dic.get('name') if my_dic else None}")
The name is None
>>> print(f"The name is {None if my_dic is None else my_dic.get('name')}")
The name is None
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Chris
  • 26,361
  • 5
  • 21
  • 42
1
my_dic = {'name': 'tom'} # return name 
# my_dic = None # return None if my_dic is None
print(f"The name is {my_dic.get('name')}" if my_dic is not None else None)