[英]Python appending to List from a nested Dictionary
我有一个嵌套字典,如下例所示:
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"},
]
我怎样才能修改我的代码来完成这个?
尝试这个
# 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 表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.