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

前端 未结 4 2081
一整个雨季
一整个雨季 2020-12-14 09:20

I have the following data structure:

  data = [
      {\'site\': \'Stackoverflow\', \'id\': 1},
      {\'site\': \'Superuser\', \'id\': 2}, 
      {\'site\':         


        
相关标签:
4条回答
  • 2020-12-14 09:49
    any(d['site'] == 'Superuser' for d in data)
    
    0 讨论(0)
  • 2020-12-14 09:52

    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.

    0 讨论(0)
  • 2020-12-14 09:57
    filter( lambda x: x['site']=='Superuser', data )
    
    0 讨论(0)
  • 2020-12-14 09:58

    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 讨论(0)
提交回复
热议问题