use*_*027 13 python printing dictionary list python-2.7
如何按照我设置的原始顺序打印出我的字典?
如果我有这样的字典:
smallestCars = {'Civic96': 12.5, 'Camry98':13.2, 'Sentra98': 13.8}
Run Code Online (Sandbox Code Playgroud)
我这样做:
for cars in smallestCars:
print cars
Run Code Online (Sandbox Code Playgroud)
它输出:
Sentra98
Civic96
Camry98
Run Code Online (Sandbox Code Playgroud)
但我想要的是这个:
Civic96
Camry98
Sentra98
Run Code Online (Sandbox Code Playgroud)
有没有办法按顺序打印原始字典而不将其转换为列表?
Pet*_*aro 19
一个普通的字典没有秩序.你需要使用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)
Run Code Online (Sandbox Code Playgroud)
输出是:
Civic96
Camry98
Sentra98
Run Code Online (Sandbox Code Playgroud)