[英]confused about dictionary in python
我有以下格言
commands = {
'cmd1':"configure terminal",
'cmd2':"router",
'cmd3':"MPLS"
}
當我執行以下代碼時:
`for cmd in commands:
print(cmd)
我總是將cmd3作為第一張打印紙,為什么?
我做錯了。
Python字典是無序的。 當您遍歷事物時,事物將以某種順序出現,但是順序可能與您添加它們的順序不同。 這是設計使然。
如果需要訂購,可以使用collections.orderedDict
。 或者,在這種情況下,由於實際上不需要密鑰,只需使用列表即可。
要查看值是什么,請使用排序后的結果列表:
for key,value in sorted(commands.items()):
print(key)
print(value)
print commands[key] # same as line above
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.