gpt4 book ai didi

python - 是否可以将新的键/值添加到字典的开头而不是后面

转载 作者:行者123 更新时间:2023-12-04 08:47:10 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您可以将字典设为 collections.OrderedDict对象并使用其 move_to_end 使用 last=False 将新键移动到字典开头的方法争论:

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'}

关于python - 是否可以将新的键/值添加到字典的开头而不是后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64252996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com