Python 从嵌套字典附加到列表

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'}]

Click here 查看完整的 ASCII table.