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()
?