Skip to content
Advertisement

Iterate through nested dictionary values and return an ordered list based on dict’s values

I have a nested dictionary titled ‘transportation_costs’ that contains the transportation costs associated with every facility-customer combination. I need to iterate through each customer (key2) in the dictionary and generate five ordered lists (one for each customer) that contains the facilities ranked from cheapest to most expensive for a given customer based on the value in the nested dictionary.

*** When I say “cheapest”, I mean it has a lower transportation cost.

 transportation_cost=
                     {'Fac-1' : {"Apple":4,"Samsung":5,"Huawei":6,"Nokia":8,"Motorolla":10},
                      'Fac-2' : {"Apple":6,"Samsung":4,"Huawei":3,"Nokia":5,"Motorolla":8},
                      'Fac-3' : {"Apple":9,"Samsung":7,"Huawei":4,"Nokia":3,"Motorolla":4},
                      'Fac-4' : {"Apple":3,"Samsung":4,"Huawei":8,"Nokia":4,"Motorolla":4},
                      'Fac-5' : {"Apple":4,"Samsung":7,"Huawei":5,"Nokia":3,"Motorolla":2}}

I need the final ouput to be something like this:

         "Apple" = ['FAC-4', 'FAC-5', 'FAC-3', 'FAC-2','FAC-1']
         "Samsung" = ['FAC-2', 'FAC-4', 'FAC-3', 'FAC-5','Fac-1']
         "Huawei"=  ['FAC-3', 'FAC-5', 'FAC-1', 'FAC-4','FAC-2']
         "Nokia" = ['FAC-5', 'FAC-3', 'FAC-2', 'FAC-4','FAC-1']
         "Motorolla" = ['FAC-5', 'FAC-1', 'FAC-3', 'FAC-2', 'FAC-4']

Advertisement

Answer

Try:

all_keys = set(k for v in transportation_cost.values() for k in v.keys())
out = {
    k: [
        *sorted(
            transportation_cost.keys(), key=lambda x: transportation_cost[x][k]
        )
    ]
    for k in all_keys
}
print(out)

Prints:

{
    "Huawei": ["Fac-2", "Fac-3", "Fac-5", "Fac-1", "Fac-4"],
    "Motorolla": ["Fac-5", "Fac-3", "Fac-4", "Fac-2", "Fac-1"],
    "Apple": ["Fac-4", "Fac-1", "Fac-5", "Fac-2", "Fac-3"],
    "Nokia": ["Fac-3", "Fac-5", "Fac-4", "Fac-2", "Fac-1"],
    "Samsung": ["Fac-2", "Fac-4", "Fac-1", "Fac-3", "Fac-5"],
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement