[Tutor] dict(a, b) does not preserve sort order

Terry Carroll carroll at tjc.com
Thu Jan 15 15:02:25 EST 2004


On Fri, 16 Jan 2004, Joel Rodrigues wrote:

> Am I wrong to be a just a wee bit annoyed about this ? :

Yes.
 
>  >>> a
> ('1', '2', '3')
>  >>> b
> ('x', 'y', 'z')
>  >>> zip(a,b)
> [('1', 'x'), ('2', 'y'), ('3', 'z')]

The above are lucky flukes.  You *cannot* depend on the keys of a 
dictionary being in sorted order.

>  >>> dict(zip(a,b))
> {'1': 'x', '3': 'z', '2': 'y'}
> 
> 
> What I expect is :
> {'1': 'x', '2': 'y', '3': 'z'}

If you need to process a dictionary in sorted-key order, use something 
along these lines:

>>> d=dict(zip(a,b))
>>> k=d.keys()
>>> k
['1', '3', '2']
>>> k.sort()
>>> k
['1', '2', '3']
>>> for foo in k:
...  print d[foo]
...
x
y
z
>>>





More information about the Tutor mailing list