Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 是否可以在字典的开头而不是后面添加新的键/值_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 是否可以在字典的开头而不是后面添加新的键/值

Python 是否可以在字典的开头而不是后面添加新的键/值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,如果我有一个dictionary:d={1:a},我想在dictionary的开头添加一个新的键和值,而不是将其添加到后面,这可能吗?例如,它将类似于: dictionary = {1:a} dictionary[2] = 'b' print(d) >>> {2:b, 1:a} 您可以将字典改为“collections.OrderedDict对象”,并使用其方法使用last=False参数将新键移动到dict的开头: from collections import Orde

如果我有一个dictionary:
d={1:a}
,我想在dictionary的开头添加一个新的键和值,而不是将其添加到后面,这可能吗?例如,它将类似于:

dictionary = {1:a}
dictionary[2] = 'b'
print(d)

>>> {2:b, 1:a}

您可以将字典改为“collections.OrderedDict对象”,并使用其方法使用
last=False
参数将新键移动到dict的开头:

from collections import OrderedDict

dictionary = OrderedDict({1: 'a'})
dictionary[2] = 'b'
dictionary.move_to_end(2, last=False)
print(dict(dictionary))
这将产生:

{2: 'b', 1: 'a'}