在python中打印字典的原始输入顺序 [英] Print original input order of dictionary in python
本文介绍了在python中打印字典的原始输入顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按原来的顺序打印出我的字典?
如果我有这样的字典: / p>
If I have a dictionary like this:
smallestCars = {'Civic96': 12.5, 'Camry98':13.2, 'Sentra98': 13.8}
我这样做:
for cars in smallestCars:
print cars
它输出:
Sentra98
Civic96
Camry98
但是我想要的是:
Civic96
Camry98
Sentra98
有没有办法打印原始字典而不将其转换为列表? p>
Is there a way to print the original dictionary in order without converting it to a list?
推荐答案
常规字典没有订单。您需要使用集合
模块的 OrderedDict
,该模块可以列出列表或元组列表,就像这样:
A regular dictionary doesn't have order. You need to use the OrderedDict
of the collections
module, which can take a list of lists or a list of tuples, just like this:
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)
输出是:
Civic96
Camry98
Sentra98
这篇关于在python中打印字典的原始输入顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文