简体   繁体   English

python帮助从列表中提取值

[英]python help with extracting value from list

lst = [{"id": 1, "name": "ernest"}, .... {"id": 16, name:"gellner"}]

for d in lst:
    if "id" in d and d["id"] == 16:
        return d

I want to extract the dictionary that the key "id" equals to "16" from the list. 我想从列表中提取键“ id”等于“ 16”的字典。

Is there a more pythonic way of this? 有没有更Python的方式呢?

Thanks in advance 提前致谢

Riffing on existing answers to get out of the comments: 整理现有答案以摆脱评论:

Consider using a generator expression when you only need the first matching element out of a sequence: 当您只需要序列中的第一个匹配元素时,请考虑使用生成器表达式:

d16 = (d for d in lst if d.get('id') == 16).next()

This is a pattern you'll see in my code often. 您会经常在我的代码中看到这种模式。 This will raise a StopIteration if it turns out there weren't any items in lst that matched the condition. 这将引发一个StopIteration ,如果事实证明有没有在任何项目lst匹配的条件。 When that's expected to happen, you can either catch the exception: 预计会发生这种情况时,您可以捕获以下异常:

try:
    d16 = (d for d in lst if d.get('id') == 16).next()
except StopIteration:
    d16 = None

Or better yet, just unroll the whole thing into a for-loop that stops 或者更好的是,将整个事情展开到一个for循环中,该循环会停止

for d16 in lst:
    if d16.get('id') == 16:
        break
else:
    d16 = None

(the else: clause only gets run if the for loop exhausts its input, but gets skipped if the for loop ends because break was used) else:子句仅在for循环用完其输入时才运行,但是如果因为使用了break而在for循环结束时被跳过)

This does it. 做到了。 Whether or not it's "cleaner" is a personal call. 是否“清洁”是个人要求。

d16 = [d for d in lst if d.get('id', 0) == 16][0]

This initial approach fails if there is no dictionary with id 0. You can overcome that somewhat like this: 如果没有ID为0的字典,则这种初始方法将失败。您可以通过以下方式克服该问题:

d16 = [d for d in lst if d.get('id', 0) == 16]
if d16: d16 = d16[0]

This will prevent the index error, but d16 will be an empty list if there is no dictionary in the container that matches the criteria. 这样可以防止索引错误,但是如果容器中没有符合条件的字典,则d16将为空列表。

如果没有发现,则有一点改进:

d16 = ([d for d in lst if d.get('id', 0) == 16] + [None])[0]

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

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