我正在搜索字典列表以查看代码是否在其中一个字典值中找到,我想做的是打印出与该代码关联的字典,如果它在列表中找到的话。
我有以下内容(打印语句显示我想做什么)。
if any(d['Code'] == responsecode for d in list_of_dicts):
print(d)
LOD 会是这样的:
list_of_dicts = [
{'Code':'2345', 'Message':'the message'},
{'Code':'1111', 'Message':'the message'}
]
响应代码类似于:1111
请您参考如下方法:
使用带有 if 的生成器表达式来过滤字典,取其 next值,如果没有发现任何内容,则使用引发的异常作为 if/else 替换:
try:
print(next(d for d in list_of_dicts if d['Code'] == responsecode))
except StopIteration:
print('Not found')
