Reputation: 23
I'd like to use list comprehension on the following list;
movie_dicts = [
{'title':'A Boy and His Dog', 'year':1975, 'rating':6.6},
{'title':'Ran', 'year':1985, 'rating': 8.3},
{'year':2010, 'rating':8.0},
{'title':'Scanners', 'year':1981, 'rating': 6.7}
]
using my knowledge of list comprehension and dictionaries, I know that
title_year = [i['title'] for i in movie_dicts]
print title_year
will print a list with movie titles. However as one of movie titles are missing i receive the following error
Traceback (most recent call last):
File "./loadjson.py", line 30, in <module>
title_year = [i['title'] for i in movie_dicts]
KeyError: 'title'
Is there any way of checking if the movie title exists placing a default value in its place if it doesn't?
Upvotes: 1
Views: 267
Reputation: 17142
Use
title_year = [i.get('title', 'defaultTitle') for i in movie_dicts]
It gives you the possibility to specify a default value if the specified key does not exist.
Upvotes: 3
Reputation: 1123490
Use the dict.get()
method to return a default for missing keys:
title_year = [i.get('title', '<untitled>') for i in movie_dicts]
This substitutes the string '<untitled>'
for missing titles. Alternatively, filter out entries without the key (producing a shorter list):
title_year = [i['title'] for i in movie_dicts if 'title' in i]
Upvotes: 4