Friday, 15 January 2010

python - Inserting value in orderedict by index? -



python - Inserting value in orderedict by index? -

let have ordered dictionary:

import collections d = collections.ordereddict([('a', none), ('b', none), ('c', none)])

and have these values in list:

lst = [10, 5, 50]

now when iterate on list, insert it's value in dictionary d list index. order need correct, don't know how insert (if possible) in dictionary index, not specifying key.

so illustration (with pseudo code here):

for in range(len(lst)): d.index(i) = lst[i] #this pseudo code, there might not such methods etc.

use zip() iterate on both dictionary keys , values list , assign values:

>>> d = collections.ordereddict([('a', none), ('b', none), ('c', none)]) >>> lst = [10, 5, 50] >>> k, val in zip(d, lst): d[k] = val ... >>> d ordereddict([('a', 10), ('b', 5), ('c', 50)])

and if know keys instead of initializing of dict first , assigning values can replaced with:

>>> keys = ['a', 'b', 'c'] >>> lst = [10, 5, 50] >>> collections.ordereddict(zip(keys, lst)) ordereddict([('a', 10), ('b', 5), ('c', 50)])

python list python-2.7 dictionary ordereddictionary

No comments:

Post a Comment