We can search for the list of dictionaries using the below some approaches, Can one please help me, which one is the memory efficient approach to use?
Provided that:
name
s are unique in the list- There will be definitely a
name
in each dictionary.
Where as:
items = [list_of_dicts]
name_to_b_searched = "some_name"
1 direct return from the for loop
def get_by_name(self, name_to_be_searched):
for i in items:
if i['name'] == name_to_be_searched:
return i
2 Break from the for loop and return found dictionary
def get_by_name(self, name_to_be_searched):
found = None
for i in items:
if i['name'] == name_to_be_searched:
found = i
break
return found
3 A generator function
def get_by_name(self, name_to_be_searched):
for i in items:
if i['name'] == name_to_be_searched:
yield i
4 An inline generator
get_by_name =next(i for i in items if i['name'] == name_to_be_searched, None)
Sometimes I could have a huge csv records (in items), so was thinking which approach would be better to search a record. OR if there is any other approach you would recommend please let me know.