Multikey Dict?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Nov 13 03:00:02 CET 2005


David Rasmussen a écrit :
> If I have a collection of dicts like:
> 
> john = {'id': 1, 'name': "John Cleese", 'year': 1939}
> graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941}
> 
> I could store all of them in a list. But for easy lookup, I might store 
> all these in a dict instead, like
> 
> people = {'1': john, '2': graham}
 > or maybe
 >
 > people = {'John Cleese': john, 'Graham Chapman': graham}

You can use integers as keys in a dict. And building an index is not 
that difficult:

peoples = [
    {'id': 1, 'name': "John Cleese", 'year': 1939},
    {id': 2, 'name': "Graham Chapman", 'year': 1941},
]

peoples_name_idx = dict((p['name'], p) for p in peoples)
peoples_id_idx = dict((p['id'], p) for p in peoples)

which generalize to:
def mk_index(index_field, records):
     return dict((rec[index_field], rec) for rec in records)

(snip)
>  would like to be able to say: 
> people['1'].year
> 
> in some case and in other cases I want to say 
> people['John Cleese'].year 

This should be:
   people['John Cleese']['year']

(If you want transform your dicts to objects so you use dotted notation, 
there are recipes for this in the Python Cookbook.)

> If I could just say to Python: john and graham (and ...) are all a part 
> of a "superdict" and either their id or their name can be used as keys.
> 
> Can I do that somehow?

Writing a dict-like object is quite easy. Look for UserDict, or directly 
subclass Dict.

Now, how could the "superdict" implementation decide which key to use ?

Here, you have a numeric 'id' and a string 'name', so you could test on 
it in __getitem__, but what if you want to use 2 different string keys? 
Computers are usually very bad at guessing, that's why we are 
programming them.



My 2 cents



More information about the Python-list mailing list