What you can do is create an index in this dictionary, for example:
cityIndex={} for item in all_dicts.values(): if item['city'] in cityIndex: cityIndex[item['city']].append(item) else: cityIndex[item['city']]=[item]
This will require some initial processing time, as well as some additional memory, but then it will be very fast. If you want all the items with some cityName , you will get them by following these steps:
mylist=cityIndex[cityName] if cityName in cityIndex else []
This gives you many benefits if all_dicts is created once and requested after that many times.
If all_dicts changes during the execution of your program, you will need one more code to support cityIndex . If item added to all_dicts , just do:
if item['city'] in cityIndex: cityIndex[item['city']].append(item) else: cityIndex[item['city']]=[item]
and if the item is deleted, this is an easy way to remove it from the index (provided that the combination of "name" and "city" is unique among your items):
for i, val in enumerate(cityIndex[item['city']]): if val['name']==item['name']: break del cityIndex[item['city']][i]
If there are many more requests than updates, you will still get a significant performance boost.
xzoert
source share