dictionary with order?

York yorklee70 at yahoo.com
Fri Mar 14 12:39:09 EST 2003


Hi, everybody

The dictionary in python add a new method -- "setdefault", that is very 
useful.
Usually items in a python dictionary have no order:
>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d
{1: 1, 2: 2}
>>> d["a"]="a"
>>> d
{'a': 'a', 1: 1, 2: 2}
>>> d["b"]="b"
>>> d
{'a': 'a', 1: 1, 2: 2, 'b': 'b'}
>>> d.keys()
['a', 1, 2, 'b']
>>> d.items()
[('a', 'a'), (1, 1), (2, 2), ('b', 'b')]

But sometimes I need keys() return the sequence:
[1, 2, "a", "b"], or items() return
[(1, 1), (2, 2), ("a", "a"), ("b", "b")]

Is it make sense to let a python dictionary arrange its items according to 
the order that an items be added in? 
for example, by add a new method "setorder" (d.setorder(1) or 
d.setorder(-1) for reverse order) to let mothods like keys(), values(), 
items() return sequence with items order same to the order for these items 
be added.

Cheers,
York





More information about the Python-list mailing list