-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselfdict.py
29 lines (27 loc) · 1.26 KB
/
selfdict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python
# @file selfdict.py
# @author Michael Foukarakis
# @version 0.1
# @date Created: Tue Oct 14, 2014 13:51 EEST
# Last Update: Tue Jan 27, 2015 18:38 EET
#------------------------------------------------------------------------
# Description: A defaultdict in which the key is also the value.
#------------------------------------------------------------------------
# History: First implementation.
# TODO: Come up with a decent name for it.
#------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------
from collections import defaultdict
class selfdict(defaultdict):
"""A selfdict is a defaultdict in which the key is also the value. This has the
following good properties:
* You can index its values using one of their properties as the key. To index
objects based on their .name, you implement the __hash__ method to hash .name
members.
* If the key is not present, the default factory will be called with the key as
the only argument.
"""
def __missing__(self, key):
self[key] = self.default_factory(key)
return self[key]