通过索引在ordereddict中插入值?

时间:2014-10-08 11:50:08

标签: python list python-2.7 dictionary ordereddictionary

假设我有这个有序词典:

import collections

d = collections.OrderedDict([('a', None), ('b', None), ('c', None)])

我在列表中有这些值:

lst = [10, 5, 50]

现在,当我遍历列表时,我希望通过该列表索引在字典d中插入它的值。所以基本上我需要的顺序是正确的,我只是不知道如何通过索引插入字典(如果可能),而不是通过指定键。

所以例如(这里有伪代码):

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

1 个答案:

答案 0 :(得分:2)

使用zip()迭代列表中的字典键和值并分配值:

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

如果你已经知道了密钥,那么首先不是初始化dict,然后为它分配值可以替换为:

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