Skip to content

Instantly share code, notes, and snippets.

@numberoverzero
Created February 10, 2015 21:22
Show Gist options
  • Select an option

  • Save numberoverzero/00fde6071ce49d54bcb5 to your computer and use it in GitHub Desktop.

Select an option

Save numberoverzero/00fde6071ce49d54bcb5 to your computer and use it in GitHub Desktop.
generate a dict mapping items by the given field of each object
"""
Generate a mapping of a list of objects by the given attr.
"""
def index(objects, attr):
return {getattr(obj, attr): obj for obj in objects}
# Example
class Person(object):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
people = [
Person('one', 'one@people.com', 1),
Person('two', 'two@people.com', 2),
Person('three', 'three@people.com', 3)
]
by_email = index(people, 'email')
by_name = index(people, 'name')
assert by_name['one'] is people[0]
assert by_email['two@people.com'] is people[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment