Home > Software engineering >  Python appending to List from a nested Dictionary
Python appending to List from a nested Dictionary

Time:06-03

I have a nested dictionary like the example below:

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": "..."},
}

I'm appending the dictionaries to a list using this code:

dev_list = []
for i in dev_dict:
    dev_list.append(dev_dict[i])

Which generates a list like this:

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": "..."},
]

What I would like to accomplish is to have the list that's generated be in a certain order based on the location's key value.

The order I'd like it to be is if the location is in the MDF then append those first, then if the location is in an IDF append those to the list after the MDF but in ascending order. So the final list would look like this:

[
    {"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"},
]

How can I modify my code to accomplish this?

CodePudding user response:

Try this

# 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 to see the complete ASCII table.

  • Related