Create dict from two lists
Iain King
iainking at gmail.com
Fri Feb 10 09:40:34 EST 2006
py wrote:
> Thanks, itertools.izip and just zip work great. However, I should have
> mentioned this, is that I need to keep the new dictionary sorted.
>
> d = {1:'first', -5 : 'negative 5', 6:'six', 99:'ninety-nine',
> 3:'three'}
> keys = d.keys()
> keys.sort()
> vals = map(d.get, keys)
>
> At this point keys is sorted [-5, 1, 3, 6, 99] and vals is sorted
> ['negative 5', 'first', 'three', 'six', 'ninety-nine']
>
> Using zip does not create the dictionary sorted in this order.
> new_d = dict(zip(keys, vals))
>
> How can I use the two lists, keys and vals to create a dictionary such
> that the items keep their order?
>
> Thanks.
Short answer - you can't. Dictionaries aren't sequential structures,
so they have no sorted form. You can iterate through it in a sorted
manner however, as long as you keep your list of keys:
keys.sort()
for k in keys:
print d[k]
Iain
More information about the Python-list
mailing list