将键值对附加到字典

时间:2015-12-03 13:52:50

标签: python

是否可以将键值对附加到字典中?

例如,我想要一个这样的字典:a = {4:"Hello", 1:"World"}可以使用字典来完成吗?如果不能,是否有可以做到的替代数据结构?

我想按顺序添加它们。在这种情况下,我首先添加了键值对4:"Hello"

3 个答案:

答案 0 :(得分:2)

from collections import OrderedDict
order_dict = OrderedDict()
order_dict[4] = "Hello"
order_dict[3] = "World"
order_dict[5] = "Bah"
print order_dict

输出:

OrderedDict([(4, 'Hello'), (3, 'World'), (5, 'Bah')])

打印键和值:

for key, value in order_dict.iteritems() :
    print key, value

输出:

4 Hello
3 World
5 Bah

答案 1 :(得分:1)

是的,可以。

从模块集合中,使用OrderedDict获取保留添加键的顺序。

答案 2 :(得分:0)

使用collections.OrderedDict订购词典:

>>> from collections import OrderedDict
>>> original = OrderedDict({1:"world"})
>>> new = OrderedDict({4:"hello"})
>>> new.update(original)
>>> new
# OrderedDict([(4, 'hello'), (1, 'World')])

这仅适用于前面的添加。对于随机位置的插入,请参阅Borja's answer

相关问题