为什么Python会像这样打印带有键的字典列表?

2024-06-01 04:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python,如果我有以下列表:

cars = {'Honda': 'Civic', 'Audi': 'A4', 'Chevrolet': 'Camaro', 'Volkswagen': 'Passat', 'Jeep': 'Wrangler', 'Pontiac': 'G6'}

Python 2.6打印如下:

print(cars)
{'Pontiac': 'G6', 'Jeep': 'Wrangler', 'Chevrolet': 'Camaro', 'Honda': 'Civic', 'Volkswagen': 'Passat', 'Audi': 'A4'}

Python 3.3打印如下:

print(cars)
{'Jeep': 'Wrangler', 'Honda': 'Civic', 'Pontiac': 'G6', 'Chevrolet': 'Camaro', 'Volkswagen': 'Passat', 'Audi': 'A4'}

Python如何确定打印项的顺序?默认情况下,不首先对列表进行排序。为什么两个版本都不按原样打印列表?这是如何实现的?你知道吗


Tags: 列表carsa4printcivicaudig6wrangler
3条回答

默认字典以随机方式打印键,因此您永远不知道它们将如何打印。如果要按顺序打印密钥,可以使用OrderedDict。你知道吗

the tutorial

It is best to think of a dictionary as an unordered set of key: value pairs...

那里的钥匙乱七八糟的。您可以使用sorted(cars)获得字典中键的排序列表。请注意,这不会将字典更改为排序类型。它只返回一个键列表。你知道吗

最好的答案是:“不要为字典的顺序操心。”

字典不是有序类型。它们使用散列存储值,并且不可排序(例如,如果调用sorted(dict),则返回list)。不要根据字典的顺序来推测它。你知道吗

如果您需要稳定的订单,请使用:

from collections import OrderedDict

cars = OrderedDict({'Honda': 'Civic', 'Audi': 'A4', 'Chevrolet': 'Camaro',\
                  'Volkswagen': 'Passat', 'Jeep': 'Wrangler', 'Pontiac': 'G6'})
#The order is now structured. You can sort it and use it as if it were ordered.

相关问题 更多 >