Code-Apprentice
Code-Apprentice

Reputation: 83517

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']?

Upvotes: 0

Views: 106

Answers (3)

Uri London
Uri London

Reputation: 10797

Also, a functional variant:

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

will return all dictionaries with the condition.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

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

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174614

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

Upvotes: 1

Related Questions