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

前端 未结 4 2080
一整个雨季
一整个雨季 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: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.

提交回复
热议问题