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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With