storing meta data on dictionary keys

Chris Mellon arkanes at gmail.com
Tue Oct 9 16:51:04 EDT 2007


On 10/9/07, Andreas Kraemer <akraemer at sbcglobal.net> wrote:
>
> I sometimes find it useful to store meta data on dictionary keys, like in
> the following example:
>
> class Dict(dict):
>   def __init__(self,*args,**kw):
>     self.key_dict = {}
>     super(Dict,self).__init__(*args,**kw)
>   def __setitem__(self,k,v):
>     self.key_dict[k] = k
>     super(Dict,self).__setitem__(k,v)
>   def get_key(self,key):
>     return self.key_dict[key]
>
> class Str(str): pass
>
> >>> friends = Dict()
> >>> friends[Str('John')] = ['Bill','Jack','Isabelle']
> >>> friends[Str('Jim')] = ['John','Bob']
> >>> friends[Str('Isabelle')] = ['John','Christine','Anabelle']
> >>> friends.get_key('John').hair_color = 'brown'
> >>> friends.get_key('Jim').hair_color = 'red'
> >>> friends.get_key('Isabelle').hair_color = 'green'
> >>> friends
> {'Jim': ['John', 'Bob'], 'John': ['Bill', 'Jack', 'Isabelle'], 'Isabelle':
> ['John', 'Christine', 'Anabelle']}
> >>> friends.get_key('Isabelle').hair_color
> 'green'
>
> A more sensible, realistic example are attributes of graph nodes (e.g.
> color, shape, etc)  in the networkx package, where node objects are stored
> as keys of (nested) dictionaries.
>
> Is there any particular reason why the built-in dictionary does not define a
> get_key() method, but only keys(), iterkeys(), and has_key() ?
>
> Cheers,
>
> Andreas
>

Because, by definition, if you have the key then you don't need to get
it from the dict. What you're doing here is conflating 2 mappings into
one: string value->person and person->values.  Use 2 explicit dicts to
make it clear what you're going, or use one dict and store a tuple of
values: person, friends = d["John"].



More information about the Python-list mailing list