简体   繁体   中英

Find a dictionary in a list of dictionaries

I have a list of dictionaries named tickets and a single dictionary named issue . How do I find the dictionary in tickets such that tickets[i]['summary'] == issue['title'] ?

You can use list comprehension like this

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

or you can use filter like this

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

Timeit Results say that the list comprehension is faster than filter and generator methods

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")

On my machine, I got

0.347553014755
0.691710948944
1.10066413879

Even if the objective is to get only one element which matches

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)

Output on my machine

0.369271993637
0.717815876007
0.557427883148

The long way, but this will search through the entire list:

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

You can make it into a function, which will will return once your dictionary is found:

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')

Or, as @Blender suggested - use a generator:

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

Also, a functional variant:

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

will return all dictionaries with the condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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