Skip to content

Instantly share code, notes, and snippets.

@specialunderwear
Created September 6, 2023 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save specialunderwear/38da69eea640eee9978aa904db37c56c to your computer and use it in GitHub Desktop.
Save specialunderwear/38da69eea640eee9978aa904db37c56c to your computer and use it in GitHub Desktop.
class KeyedItems(dict):
"""
KeyedItems allow you to create a dict from a list of dicts, keyed by the parameter passed
as key. If no param is passed the entire item will be the key. KeyedItems will
not process the entire list, but processing will only proceed up to the item
that you requested was found, saving memory and processing time.
This is demonstrated below by using an infinite list generated by count.
>>> from itertools import count
>>> x = KeyedItems(({"koe": y} for y in count()), key="koe")
>>> x.get(4)
{'koe': 4}
>>> a = KeyedItems(count())
>>> a.get(100)
100
"""
def __init__(self, items, key=None):
# use an iterator so the list can only be traversed once.
self.items = iter(items)
self.key = key
def get(self, key, default=None):
try:
return self[key]
except KeyError:
for item in self.items:
item_key = item[self.key] if self.key else item
self[item_key] = item
if item_key == key:
return item
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment