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

David Rock david at graniteweb.com
Thu Jan 15 14:14:49 EST 2004


* Joel Rodrigues <joelrodrigues at ifrance.com> [2004-01-16 00:08]:
> Am I wrong to be a just a wee bit annoyed about this ? :
> 
> >>> a
> ('1', '2', '3')
> >>> b
> ('x', 'y', 'z')
> >>> zip(a,b)
> [('1', 'x'), ('2', 'y'), ('3', 'z')]
> >>> dict(zip(a,b))
> {'1': 'x', '3': 'z', '2': 'y'}
> 
> 
> What I expect is :
> {'1': 'x', '2': 'y', '3': 'z'}

Yes, you are ;-)

Dictonaries are not sorted lists. The information is based on key:value
relationships that have nothing to do with the order they exist in the
dictionary. To access the value for a given key, simply ask for it:

>>> d = dict(zip(a,b))
>>> d[1]
x
>>> d[2]
y
>>> d[3]
z

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20040115/c5fb2bde/attachment.bin


More information about the Tutor mailing list