Most efficient way to search in list of dicts

后端 未结 2 566
無奈伤痛
無奈伤痛 2020-12-15 22:23

I have the following list of dicts.

people = [
{\'name\': \"Tom\", \'age\': 10},
{\'name\': \"Mark\", \'age\': 5},
{\'name\': \"Pam\", \'age\': 7}
]
<         


        
2条回答
  •  猫巷女王i
    2020-12-15 23:10

    If you are searching for a single item then this is the "best" approach

    def search(name):
        for p in people:
            if p['name'] == name:
                return p
    

    All the other implementations will iterate over all the items in the list, whereas this one will stop once the item is found

提交回复
热议问题