简体   繁体   English

如何根据类似的值和键对python字典进行排序?

[英]How to sort python dictionary based on similar values and keys?

In my case, i have a random values of dictionary like this : 就我而言,我有一个随机的字典值,如下所示:

dict = {2: 1, 27: 28, 56: 28, 57: 29, 58: 29, 59: 29, 28: 29, 29: 1, 30: 1, 31: 1}

if i illustrate that dictionary into hierarchy chart, it will be like this : 如果我将该字典说明为层次结构图,它将是这样的: 在此输入图像描述

my goal are to sorting that dictionary sequenced by its values than following by similar keys in parallel into a list. 我的目标是将按其值排序的字典排序,然后将类似的键并行排列到列表中。 for example, if we start from keys = 27, so the result will be like this : 例如,如果我们从keys = 27开始,那么结果将是这样的:

list = [ 27, 28, 29, 1 ]

is there any idea to solve this problem or whether python has a capabilities library to solve it ? 有什么想法解决这个问题或者python是否有能力库来解决它?

What are you looking seems to be the path to the root where each key in the dictionary maps to its parent. 你在寻找什么似乎是根的路径,其中字典中的每个键映射到其父级。 Using a generator function the problem can be solved easily: 使用生成器功能可以轻松解决问题:

d = {2: 1, 27: 28, 56: 28, 57: 29, 58: 29, 59: 29, 28: 29, 29: 1, 30: 1, 31: 1}

def path_to_root(d, start):
    yield start
    while start in d:
        start = d[start]
        yield start

print list(path_to_root(d, 27))

Result: 结果:

[27, 28, 29, 1]

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

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