miscoranda: by Sean B. Palmer

List-Dictionary Hybrid

The Listdict class implemented in listdict.py is a port of the array-dict type from Javascript to Python. It has the properties of both Python lists and Python dicts, as is illustrated by the following code:

>>> from listdict import Listdict
>>> arr = Listdict({5: 'chicken', 7: 'chickette'})
>>> len(arr)                 
8
>>> arr[5], arr[15]
('chicken', None)
>>> arr[5:8]
{0: 'chicken', 1: None, 2: 'chickette'}
>>> arr.pop()
'chickette'
>>> len(arr)
7
>>> arr['hmm'] = 'heh'
>>> arr.has_key(5)  
True
>>> 'chicken' in arr
True
>>> 'heh' in arr
False
>>> arr.sort()
>>> arr.reverse()
>>> arr.truncate(2)
>>> print arr
{0: 'chicken', 1: None, 'hmm': 'heh'}
>>> 

There's a test suite in the module itself which displays some of the other functionality of the Listdict class. The original idea was inspired by Jim Ley, who pointed out the lack of this useful feature prompting me to implement it, which I did in about an hour with commentary to the #svg channel.

Update: the code previously required Python 2.4, but it now works in Python 2.3 with the exception of sorting and reversing. The code is in the same place. Many thanks to Dave Pawson for the nudge.

by Sean B. Palmer, at 2005-05-24 06:18:33. Comment?

Imkrozh - An English Cipher · Origins of Jabberwocky

Sean B. Palmer