Created
February 10, 2015 21:22
-
-
Save numberoverzero/00fde6071ce49d54bcb5 to your computer and use it in GitHub Desktop.
generate a dict mapping items by the given field of each object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| 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