Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch KeyError in a python for loop with lambda function?

Is it possible to catch a KeyError for x['uri'] for this particular scenario.

joined_rooms = ('coala/coala', 'coala/coala-bears')
room_data = [{'id': '130', 'uri': 'coala/coala'},
             {'id': '234', 'name': 'Nitanshu'},
             {'id': '897', 'uri': 'coala/coala-bears'}]

for room in filter(lambda x: x['uri'] in joined_rooms, room_data):
    #do stuff

Doing this:

try:
    for room in filter(lambda x: x['uri'] in joined_rooms, room_data):
        #do stuff
except KeyError:
    pass

will skip all the items after KeyError is raised.

Is there any way to handle this apart from migrating to the classic nested for loops with if condition?

like image 474
Nitanshu Avatar asked Mar 20 '26 21:03

Nitanshu


1 Answers

Python dicts have a get method for just such an occasion. It takes two arguments, first is the key you're looking for, second is the default value to use if the key is not present in the dictionary. Try this:

for room in filter(lambda x:x.get('uri',None) in joined_rooms, room_data):
    #do stuff

The problem here, although it might not be a problem in your case, is that you're left with needing to supply a default value that will never appear in joined_rooms.

like image 139
mypetlion Avatar answered Mar 23 '26 10:03

mypetlion