我有一个字典,我不断更新购买使用.update添加新的值和密钥,在循环中添加新密钥。我希望字典按照我添加它们的顺序打印出值。这可能吗?
答案 0 :(得分:4)
您需要使用array而不是标准词典。它将保持秩序,但在其他方面就像一个正常的字典。
答案 1 :(得分:0)
为此,您可以使用OrderedDict
,因为它会记住其内容的添加顺序。它是普通Python字典的子类,因此可以访问字典的所有功能。
示例:强>
In [1]: import collections
In [2]: normal_dict = {}
In [3]: normal_dict['key1'] = 1 # insert key1
In [4]: normal_dict['key2'] = 2 # insert key2
In [5]: normal_dict['key3'] = 3 # insert key3
In [6]: for k,v in normal_dict.items(): # print the dictionary
...: print k,v
...:
key3 3 # order of insertion is not maintained
key2 2
key1 1
In [7]: ordered_dict = collections.OrderedDict()
In [8]: ordered_dict['key1'] = 1 # insert key1
In [9]: ordered_dict['key2'] = 2 # insert key2
In [10]: ordered_dict['key3'] = 3 # insert key3
In [11]: for k,v in ordered_dict.items(): # print the dictionary
print k,v
....:
key1 1 # order of insertion is maintained
key2 2
key3 3