【发布时间】:2015-12-26 01:58:07
【问题描述】:
我有一本字典,我使用 .update 不断更新购买以添加新值和键,并在循环时添加新键。我希望字典按照我添加它们的顺序打印出这些值。这可能吗?
【问题讨论】:
-
标准字典不考虑顺序。请改用OrderedDict。顺便说一句,这已在 SO 上多次讨论过:1、2、3、4、...
标签: python sorting dictionary
我有一本字典,我使用 .update 不断更新购买以添加新值和键,并在循环时添加新键。我希望字典按照我添加它们的顺序打印出这些值。这可能吗?
【问题讨论】:
标签: python sorting dictionary
您需要使用OrderedDict 而不是标准字典。它会保持顺序,但在其他方面就像一个普通的字典。
【讨论】:
为此,您可以使用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
【讨论】: