简体   繁体   English

如何使用lambda函数在Python for循环中捕获KeyError?

[英]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. 对于这种特定情况,是否有可能捕获x['uri']KeyError

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. 引发KeyError后将跳过所有项目。

Is there any way to handle this apart from migrating to the classic nested for loops with if condition ? 除了使用if condition迁移到经典的嵌套for loops之外,还有什么方法可以解决此if condition

Python dict s have a get method for just such an occasion. 在这种情况下,Python dict就有了get方法。 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 . 尽管您的情况可能不是问题,但是这里的问题是,您需要提供一个永远不会出现在joined_rooms的默认值。

As mentioned, you can use dict.get to return a default value if a key does not exist in a dictionary. 如前所述,如果字典中不存在键,则可以使用dict.get返回默认值。 If not provided, this default value is None . 如果未提供,则此默认值为None

As an alternative, you can use a generator expression. 或者,您可以使用生成器表达式。 This will be more efficient than filter + lambda expression. 这将比filter + lambda表达式更有效。 It may also be more readable: 它也可能更具可读性:

for room in (x for x in room_data if x.get('iri') in joined_rooms):
    # do something

Another perfectly valid solution is to use an if statement within your for loop: 另一个完全有效的解决方案是在for循环中使用if语句:

for room in room_data:
    if 'iri' in room:
        # do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM