Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.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_Sorting_Dictionary - Fatal编程技术网

python中的词典排序

python中的词典排序,python,sorting,dictionary,Python,Sorting,Dictionary,我有一个字典,我一直在用它更新buy。update来添加一个新的值和键,在循环中添加新的键。我希望字典按照我添加值的顺序打印出这些值。这可能吗?您需要使用标准词典,而不是标准词典。它将保持顺序,但在其他方面的行为与正常的命令类似。要做到这一点,您可以使用一个,因为它会记住添加内容的顺序。它是普通Python字典的子类,因此可以访问字典的所有功能 示例: In [1]: import collections In [2]: normal_dict = {} In [3]: normal_dic

我有一个字典,我一直在用它更新buy。update来添加一个新的值和键,在循环中添加新的键。我希望字典按照我添加值的顺序打印出这些值。这可能吗?

您需要使用标准词典,而不是标准词典。它将保持顺序,但在其他方面的行为与正常的命令类似。

要做到这一点,您可以使用一个,因为它会记住添加内容的顺序。它是普通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

标准词典不考虑顺序。改用。顺便说一句,这已经在这里讨论过好几次了,所以:。。。