python怎么打印字典_在python中打印字典的原始输入顺序
如何按照我設置的原始順序打印出我的字典?
如果我有這樣的字典:
smallestCars = {'Civic96': 12.5, 'Camry98':13.2, 'Sentra98': 13.8}
我這樣做:
for cars in smallestCars:
print cars
它輸出:
Sentra98
Civic96
Camry98
但我想要的是這個:
Civic96
Camry98
Sentra98
有沒有辦法按順序打印原始字典而不將其轉換為列表?
解決方法:
普通字典沒有訂單.您需要使用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)
輸出是:
Civic96
Camry98
Sentra98
標簽:python,list,python-2-7,dictionary,printing
來源: https://codeday.me/bug/20191007/1867874.html
總結
以上是生活随笔為你收集整理的python怎么打印字典_在python中打印字典的原始输入顺序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: openssl漏洞怎么处理_以太坊UDP
- 下一篇: 支持python开发的环境有哪些变化_P