【问题标题】:Inserting value in orderedict by index?按索引在ordereddict中插入值?
【发布时间】:2014-12-03 01:47:07
【问题描述】:

假设我有这个有序字典:

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.

【问题讨论】:

  • 更新任意位置的值,d[d.keys()[i]]=....

标签: python list python-2.7 dictionary ordereddictionary


【解决方案1】:

使用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)])

如果您已经知道键,那么可以替换为:

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

【讨论】:

  • 谢谢,这很整洁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 2018-09-13
  • 2017-06-05
  • 2011-09-05
相关资源
最近更新 更多