0

I have a list of dicts where some fields can be None:

d = [ {'name' : 'Jimmy', 'surname' : 'Page', 'title' : None}, {'name' : 'Brian', 'surname' : 'May', 'title' : 'Mr.'} ]

I'm iterating over each dict in the list to do something (e.g. print it all as lowercase):

for item in d:
    print(item.get('name').lower())
    print(item.get('surname').lower())
    print(item.get('title').lower())

This of course will fail as soon as it encounters a None type:

jimmy
page
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print(item.get('title').lower())
AttributeError: 'NoneType' object has no attribute 'lower'

Without resorting to try..except blocks or using if statements for each key of the dict, is there a way to check if item.get() returns None before calling .lower()?

Chef Tony
  • 435
  • 7
  • 14
  • 1
    This is what you were looking for: https://stackoverflow.com/questions/11880430/how-to-write-inline-if-statement-for-print – mkrieger1 Oct 03 '22 at 21:31

1 Answers1

0

I've figured out what I need to do this inline is called "ternary operator":

print(None if item.get('title') is None else item.get('title').lower())
Chef Tony
  • 435
  • 7
  • 14