循环访问嵌套的字典值,并根据字典的值返回有序列表



我有一个名为'transportation_costs'的嵌套字典,其中包含与每个设施-客户组合相关联的运输成本。我需要遍历字典中的每个客户(key2),并生成五个有序列表(每个客户一个),其中包含基于嵌套字典中的值对给定客户从最便宜到最昂贵的设施。

***当我说"最便宜"的时候,我的意思是它的运输成本更低。

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

我需要的最终输出是这样的:

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

尝试:

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)

打印:

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

相关内容

  • 没有找到相关文章

最新更新