【发布时间】:2021-12-14 04:54:26
【问题描述】:
我有一本字典,其中的值是字典列表:
{ 'client1':
[
{ 'id': 123, 'name': 'test1', 'number': 777 },
{ 'id': 321, 'name': 'test2', 'number': 888 },
{ 'id': 456, 'name': 'test3', 'number': 999 }
],
...
}
clientX 有很多条目键。
现在,为了获取条目,例如name == test2,我遍历列表并检查 name 值,如下所示:
for l in d['client']:
if 'test2' in l['name']:
# process the entry
...
是否有更短/紧凑的方法来进行此类查找?
【问题讨论】:
-
你说你想用
name == test2获取条目,但是在你写'test2' in l['name']的代码中这是另一回事。一是平等,二是包容。那么你真正想要获取什么? -
这个表达式是线性搜索最简单的表达式。在我的建议中,您可以在“if-else 子句”的末尾添加一个 break 语句以使其运行得更快
-
这能回答你的问题吗? Python list of dictionaries search
-
'test2' in l['name']也将是true如果l[name]是'test22'这是不正确的 -
@nadapez,我明白了,这有很大的不同。所以
in不执行完全匹配。
标签: python python-2.7 dictionary