Create dict from two lists

py codecraig at gmail.com
Fri Feb 10 09:20:43 EST 2006


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.




More information about the Python-list mailing list