expression form of one-to-many dict?

Steven Bethard steven.bethard at gmail.com
Fri Dec 17 17:09:47 EST 2004


Tim Peters wrote:
>>The point here is that there's a simple sequence or GE that I can
>>throw to the dict constructor that spits out a dict with my one-to-
>>one mapping.
> 
> 
> It's a simple sequence because it's a simple task.  It's even simpler
> than perhaps it "should be", since it arbitrarily decides that, if
> more than one instance of some key is seen, it will only remember the
> value associated with the last instance of that key.

Good point.  That's sort of an arbitrary behavior decision, which, while 
reasonable in most situations is not desirable in mine.  In thinking 
about this, it struck me that one solution is to change that behavior:

 >>> class OneToMany(object, UserDict.DictMixin):
...     def __init__(*args, **kwds):
...         self, args = args[0], args[1:]
...         self._dict = {}
...         self.update(*args, **kwds)
...     def __getitem__(self, key):
...         if not key in self._dict:
...             self._dict[key] = []
...         return self._dict[key]
...     def __setitem__(self, key, value):
...         self[key].append(value)
...     def keys(self):
...         return self._dict.keys()
...
 >>> d = OneToMany((pow(i, 13, 4), i) for i in range(10))
 >>> d[0]
[0, 2, 4, 6, 8]
 >>> d[1]
[1, 5, 9]
 >>> d[3]
[3, 7]

I'll have to think about whether it would be worth keeping a class like 
this around...  It might make working with this kind of data 
interactively simpler...

Thanks for the comments!

Steve



More information about the Python-list mailing list