简体   繁体   English

遍历嵌套的字典值并返回基于字典值的有序列表

[英]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.我有一个名为“transportation_costs”的嵌套字典,其中包含与每个设施-客户组合相关的运输成本。 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.我需要遍历字典中的每个客户 (key2) 并生成五个有序列表(每个客户一个),其中包含根据嵌套字典中的值对给定客户从最便宜到最昂贵排名的设施。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM