我有一個嵌套字典,如下例所示:
dev_dict = {
"switch-1": {"hostname": "switch-1.nunya.com", "location": "IDF01"},
"switch-2": {"hostname": "switch-2.nunya.com", "location": "IDF02"},
"...": {"hostname": "...", "location": "..."},
"switch-30": {"hostname": "switch-30.nunya.com", "location": "IDF30"},
"router-1": {"hostname": "router-a-1.nunya.com", "location": "MDF"},
"core-1": {"hostname": "core-1.nunya.com", "location": "MDF"},
"...": {"hostname": "...", "location": "..."},
}
我正在使用以下代碼將字典附加到串列中:
dev_list = []
for i in dev_dict:
dev_list.append(dev_dict[i])
這會生成一個這樣的串列:
dev_list = [
{"hostname": "switch-30.nunya.com", "location": "IDF30"},
{"hostname": "core-1.nunya.com", "location": "MDF"},
{"hostname": "switch-2.nunya.com", "location": "IDF02"},
{"hostname": "...", "location": "..."},
{"hostname": "router-1.nunya.com", "location": "MDF"}
{"hostname": "...", "location": "..."},
]
我想要完成的是讓生成的串列根據location
的鍵值按特定順序排列。
我希望它的順序是如果位置在MDF
然后附加那些第一個,然后如果位置在IDF
附加到串列之后MDF
但按升序排列。所以最終串列看起來像這樣:
[
{"hostname": "router-1.nunya.com", "location": "MDF"},
{"hostname": "core-1.nunya.com", "location": "MDF"},
{"hostname": "...", "location": "..."},
{"hostname": "switch-1.nunya.com", "location": "IDF01"},
{"hostname": "switch-2.nunya.com", "location": "IDF02"},
{"hostname": "...", "location": "..."},
{"hostname": "switch-30.nunya.com", "location": "IDF30"},
]
我怎樣才能修改我的代碼來完成這個?
uj5u.com熱心網友回復:
嘗試這個
# add a white space before MDF if location is MDF so that MDF locations come before all others
# (white space has the lowest ASCII value among printable characters)
sorted(dev_dict.values(), key=lambda d: " MDF" if (v:=d['location'])=='MDF' else v)
# another, much simpler way (from Olvin Roght)
sorted(dev_dict.values(), key=lambda d: d['location'].replace('MDF', ' MDF'))
# [{'hostname': 'router-a-1.nunya.com', 'location': 'MDF'},
# {'hostname': 'core-1.nunya.com', 'location': 'MDF'},
# {'hostname': '...', 'location': '...'},
# {'hostname': 'switch-1.nunya.com', 'location': 'IDF01'},
# {'hostname': 'switch-2.nunya.com', 'location': 'IDF02'},
# {'hostname': 'switch-30.nunya.com', 'location': 'IDF30'}]
單擊此處查看完整的 ASCII 表。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487392.html