Created
July 19, 2013 09:47
-
-
Save tokibito/6038009 to your computer and use it in GitHub Desktop.
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
DATA = [ | |
{'number': 2, 'name': 'b'}, | |
{'number': 1, 'name': 'a'}, | |
{'number': 4, 'name': 'd'}, | |
] | |
class Picker(object): | |
def __init__(self, lst, key_func=lambda v: v): | |
self.lst = lst | |
self.key_func = key_func | |
def __getitem__(self, match): | |
for value in self.lst: | |
key = self.key_func(value) | |
if key == match: | |
return value | |
def main(): | |
""" | |
>>> main() | |
1, a | |
2, b | |
3, None | |
4, d | |
5, None | |
""" | |
picker = Picker(DATA, lambda v: v['number']) | |
for i in range(1, 6): | |
value = picker[i] | |
print("{}, {}".format(i, value and value['name'])) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment