在字典列表中查找字典

时间:2013-11-17 04:23:11

标签: python list dictionary

我有一个名为tickets的词典列表和一个名为issue的词典。如何在tickets中找到tickets[i]['summary'] == issue['title']

的词典

3 个答案:

答案 0 :(得分:2)

你可以像这样使用列表理解

print [ticket for ticket in tickets if ticket['summary'] == issue['title']]

或者你可以像这样使用filter

print filter(lambda ticket: ticket["summary"] == issue["title"], tickets)

Timeit Results表示列表理解比过滤器和生成器方法更快

tickets = [{"summary" : "a"}, {"summary" : "a"}, {"summary" : "b"}]
issue = {"title" : "a"}
from timeit import timeit
print timeit("[ticket for ticket in tickets if ticket['summary'] == issue['title']]", setup="from __main__ import tickets, issue")
print timeit('filter(lambda ticket: ticket["summary"] == issue["title"], tickets)', setup="from __main__ import tickets, issue")
print timeit("list(ticket for ticket in tickets if ticket['summary'] == issue['title'])", setup="from __main__ import tickets, issue")

在我的机器上,我得到了

0.347553014755
0.691710948944
1.10066413879

即使目标是只获得一个匹配

的元素
tickets = [{"summary" : "a"}, {"summary" : "a"}, {"summary" : "b"}]
issue = {"title" : "a"}
setupString = "from __main__ import tickets, issue"
from timeit import timeit
print timeit("[ticket for ticket in tickets if ticket['summary'] == issue['title']][0]", setup=setupString)
print timeit('filter(lambda ticket: ticket["summary"] == issue["title"], tickets)[0]', setup=setupString)
print timeit("next(ticket for ticket in tickets if ticket['summary'] == issue['title'])", setup=setupString)

我机器上的输出

0.369271993637
0.717815876007
0.557427883148

答案 1 :(得分:2)

很长一段路,但这将搜索整个列表:

for i in tickets:
   if i['summary'] == issue['title']:
      print('Found it!')
   else:
      print('Does not exist')

你可以把它变成一个函数,一旦找到你的字典就会返回它:

def search(k, n):
    for i in k:
       if i['summary'] == n['title']:
           return i

results = search(tickets, issue)
if not results:
   print('No matching ticket found')

或者,正如@Blender建议的那样 - 使用生成器:

result = next(t for t in tickets if t['summary'] == issue['title'])

答案 2 :(得分:0)

另外,功能变体:

filter (lambda dict: dict['summary'] == issue['title'], tickets)

将返回所有带有条件的词典。