Skip to main content
 首页 » 编程设计

python之如何获取列表中字典的索引

2025年05月04日92zhoujg

test = [{"first" : "xyz", 'score': [1,2,3,4]},{"first" : "tests", 'score': [22,33,4]}] 

我试图在测试中找到 xyz 并列出 xyz 的分数。

请您参考如下方法:

您可以在 next 中使用生成器表达式功能:

>>> next(d['score'] for d in test if test and d['first']=='xyz') 
[1, 2, 3, 4] 

但由于有可能字典中不存在某个键,您可以使用try-except 表达式来处理错误:

>>> try : 
...    next(d['score'] for d in test if test and d['first']=='xyz') 
... except KeyError: 
...    #proper error message