storing meta data on dictionary keys

Andreas Kraemer akraemer at sbcglobal.net
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 = {}
    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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071009/a8e0a764/attachment.html>


More information about the Python-list mailing list