Wednesday, August 24, 2011

A Dictionary of Links

I wanted a dictionary of links for an MD type simulation, and I wanted the links to be unique, and I didn't want to have to check for the order the guys appeared in the dictionary keys every time, so I wrote my own dictionary by extending the native one.



Where I put that code on gist. To pull it off, you see that I subclass dict, and define a decorator that pulls out and sorts the first argument. After that it is just decorating the '__setitem__','__getitem__',and '__delitem__' methods. This lets us do nice things now:

>>> z = Links()
>>> z[1,2] = 5
>>> z[4,3] = 10
>>> z
{(1, 2): 5, (3, 4): 10}
>>> z[2,1]
5
>>> z[1,2]
5
>>> z[2,1] = 11
>>> z
{(1, 2): 11, (3, 4): 10}
>>> del z[2,1]
>>> (3,4) in z
True
>>> (4,3) in z
True
>>> z
{(3, 4): 10}
>>> z[5] = 1
Traceback (most recent call last):
  File "", line 1, in 
  File "links.py", line 10, in orderedversion
    assert hasattr(first,"__len__"), "Key must be iterable"
AssertionError: Key must be iterable
>>> z[4,4,3] = 1
Traceback (most recent call last):
  File "", line 1, in 
  File "links.py", line 11, in orderedversion
    assert len(first)==2, "Key must be 2-tuple"
AssertionError: Key must be 2-tuple
>>> z
{(3, 4): 10}

No comments:

Post a Comment