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.
JavaScript
x
7
1
transportation_cost=
2
{'Fac-1' : {"Apple":4,"Samsung":5,"Huawei":6,"Nokia":8,"Motorolla":10},
3
'Fac-2' : {"Apple":6,"Samsung":4,"Huawei":3,"Nokia":5,"Motorolla":8},
4
'Fac-3' : {"Apple":9,"Samsung":7,"Huawei":4,"Nokia":3,"Motorolla":4},
5
'Fac-4' : {"Apple":3,"Samsung":4,"Huawei":8,"Nokia":4,"Motorolla":4},
6
'Fac-5' : {"Apple":4,"Samsung":7,"Huawei":5,"Nokia":3,"Motorolla":2}}
7
I need the final ouput to be something like this:
JavaScript
1
6
1
"Apple" = ['FAC-4', 'FAC-5', 'FAC-3', 'FAC-2','FAC-1']
2
"Samsung" = ['FAC-2', 'FAC-4', 'FAC-3', 'FAC-5','Fac-1']
3
"Huawei"= ['FAC-3', 'FAC-5', 'FAC-1', 'FAC-4','FAC-2']
4
"Nokia" = ['FAC-5', 'FAC-3', 'FAC-2', 'FAC-4','FAC-1']
5
"Motorolla" = ['FAC-5', 'FAC-1', 'FAC-3', 'FAC-2', 'FAC-4']
6
Advertisement
Answer
Try:
JavaScript
1
11
11
1
all_keys = set(k for v in transportation_cost.values() for k in v.keys())
2
out = {
3
k: [
4
*sorted(
5
transportation_cost.keys(), key=lambda x: transportation_cost[x][k]
6
)
7
]
8
for k in all_keys
9
}
10
print(out)
11
Prints:
JavaScript
1
8
1
{
2
"Huawei": ["Fac-2", "Fac-3", "Fac-5", "Fac-1", "Fac-4"],
3
"Motorolla": ["Fac-5", "Fac-3", "Fac-4", "Fac-2", "Fac-1"],
4
"Apple": ["Fac-4", "Fac-1", "Fac-5", "Fac-2", "Fac-3"],
5
"Nokia": ["Fac-3", "Fac-5", "Fac-4", "Fac-2", "Fac-1"],
6
"Samsung": ["Fac-2", "Fac-4", "Fac-1", "Fac-3", "Fac-5"],
7
}
8