storing meta data on dictionary keys

Andreas Kraemer akraemer at
Tue Oct 9 20:18:51 CEST 2007

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 = {}
  def __setitem__(self,k,v):
    self.key_dict[k] = k
  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

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() ?



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list