在python中打印字典的原始输入顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20110627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print original input order of dictionary in python
提问by user2989027
How do I print out my dictionary in the original order I had set up?
如何按照我设置的原始顺序打印我的字典?
If I have a dictionary like this:
如果我有这样的字典:
smallestCars = {'Civic96': 12.5, 'Camry98':13.2, 'Sentra98': 13.8}
and I do this:
我这样做:
for cars in smallestCars:
print cars
it outputs:
它输出:
Sentra98
Civic96
Camry98
but what I want is this:
但我想要的是:
Civic96
Camry98
Sentra98
Is there a way to print the original dictionary in order without converting it to a list?
有没有办法按顺序打印原始字典而不将其转换为列表?
采纳答案by Peter Varo
A regulardictionary doesn't have order. You need to use the OrderedDictof the collectionsmodule, which can take a list of lists or a list of tuples, just like this:
一个普通的字典没有秩序。你需要使用OrderedDict的的collections模块,这可能需要一个列表的列表或元组列表,就像这样:
import collections
key_value_pairs = [('Civic86', 12.5),
('Camry98', 13.2),
('Sentra98', 13.8)]
smallestCars = collections.OrderedDict(key_value_pairs)
for car in smallestCars:
print(car)
And the output is:
输出是:
Civic96
Camry98
Sentra98
回答by Amadan
Dictionaries are not required to keep order. Use OrderedDict.
字典不需要保持秩序。使用OrderedDict.
回答by Sweeney Todd
When you create the dictionary, python doesn't care about in what order you wrote the elements and it won't remember the order after the object is created. You cannot expect it(regular dictionary) to print in the same order. Changing the structure of your code is the best option you have here and the OrderedDictis a good option as others stated.
创建字典时,python 不关心您编写元素的顺序,并且不会记住对象创建后的顺序。您不能期望它(常规词典)以相同的顺序打印。更改代码的结构是您在这里拥有的最佳选择,正如其他人所说的,OrderedDict是一个不错的选择。
回答by sinceq
>>> for car in sorted(smallestCars.items(),key=lambda x:x[1]):
... print car[0]
...
Civic96
Camry98
Sentra98
回答by brandonscript
You can use a tuple (nested) array to do this:
您可以使用元组(嵌套)数组来执行此操作:
smallestCars = [['Civic86', 12.5],
['Camry98', 13.2],
['Sentra98', 13.8]]
for car, size in smallestCars:
print(car, size)
# ('Civic86', 12.5)
# ('Camry98', 13.2)
# ('Sentra98', 13.8)

