Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否按索引在OrderDecit中插入值?_Python_List_Python 2.7_Dictionary_Ordereddictionary - Fatal编程技术网

Python 是否按索引在OrderDecit中插入值?

Python 是否按索引在OrderDecit中插入值?,python,list,python-2.7,dictionary,ordereddictionary,Python,List,Python 2.7,Dictionary,Ordereddictionary,假设我有一本有序字典: import collections d = collections.OrderedDict([('a', None), ('b', None), ('c', None)]) 我在列表中列出了这些值: lst = [10, 5, 50] 现在,当我迭代列表时,我想通过该列表索引在dictionaryd中插入它的值。所以基本上我需要的顺序是正确的,我只是不知道如何在字典中按索引插入(如果可能的话),而不是指定键 例如(这里使用伪代码): 用于迭代字典键和列表中的值,并

假设我有一本有序字典:

import collections

d = collections.OrderedDict([('a', None), ('b', None), ('c', None)])
我在列表中列出了这些值:

lst = [10, 5, 50]
现在,当我迭代列表时,我想通过该列表索引在dictionary
d
中插入它的值。所以基本上我需要的顺序是正确的,我只是不知道如何在字典中按索引插入(如果可能的话),而不是指定键

例如(这里使用伪代码):

用于迭代字典键和列表中的值,并分配值:

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

谢谢,这很好。要在任意位置更新值,
d[d.keys()[i]=…
>>> keys = ['a', 'b', 'c']
>>> lst = [10, 5, 50]
>>> collections.OrderedDict(zip(keys, lst))
OrderedDict([('a', 10), ('b', 5), ('c', 50)])