简体   繁体   English

在python中打印字典的原始输入顺序

[英]Print original input order of dictionary in python

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? 有没有办法按顺序打印原始字典而不将其转换为列表?

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: 您需要使用collections模块的OrderedDict ,它可以获取列表列表或元组列表,如下所示:

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

Dictionaries are not required to keep order. 字典不需要保持秩序。 Use OrderedDict . 使用OrderedDict

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. 当您创建字典时,python不关心您编写元素的顺序,并且在创建对象后它不会记住顺序。 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 OrderedDict is a good option as others stated. 更改代码的结构是您在这里的最佳选择, OrderedDict是一个很好的选择,正如其他人所说。

>>> for car in sorted(smallestCars.items(),key=lambda x:x[1]):
...     print car[0]
... 
Civic96
Camry98
Sentra98

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM