Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to search for a Python dictionary value in a list of dictionaries?

Tags:

python

I have the following data structure:

  data = [
      {'site': 'Stackoverflow', 'id': 1},
      {'site': 'Superuser', 'id': 2}, 
      {'site': 'Serverfault', 'id': 3}
  ]

I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?

like image 310
Thierry Lam Avatar asked Oct 16 '09 20:10

Thierry Lam


1 Answers

any(d['site'] == 'Superuser' for d in data)
like image 55
Lukáš Lalinský Avatar answered Sep 29 '22 11:09

Lukáš Lalinský