开发者

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

开发者 https://www.devze.com 2022-12-08 13:35 出处:网络
I have the following data structure: data = [ {\'site\': \'Stackoverflow\', \'id\': 1}, {\'site\': \'Superuser\', \'id\': 2},

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/Fa开发者_Python百科lse. 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?


any(d['site'] == 'Superuser' for d in data)


filter( lambda x: x['site']=='Superuser', data )


Lists absolutely require loops. That's what lists are for.

To avoid looping you have to avoid lists.

You want dictionaries of search keys and objects.

sites = dict( (d['site'],d) for d in data )
ids = dict( (d['id'],d] for d in data )

Now you can find the item associated with 'Superuser' with sites["Superuser"] using a hashed lookup instead of a loop.


I'm not sure of the python syntax, but it might work for you this way. While building your primary data structure, also build a parallel one that's a hash or associative array keyed on the site name; then to see if a given site exists you attempt a lookup in the hash with the site name. If it succeeds, you know there's a record in your data structure for that site and you've done it in the time of the hash lookup (likely O(1) or O(log2(n)) depending on the hash technique) instead of the O(n/2) of the list traversal.

(updated while writing: this is pretty much what S.Lott posted)

0

精彩评论

暂无评论...
验证码 换一张
取 消