在python中按连接顺序对字典的值进行排序

问题描述

我试图找到一种解决方案。也许我的话选错了。对不起,我的英语。

我有字典。

  • 每个键都有两个值
  • 除了两个以外,所有键都有相同的值。
  • 您将了解,这是一条链。现在,我知道我无法订购字典,所以我想知道是否可以在列表中排列值。 我发现了一些接近的东西,但仍然无法正常工作。

d= {'A': [tg,17],'B': [59,60],'C': [60,61],'D': [57,tt],'E': [61,tg],'F': [tt,59]}

sorted_keys = sorted(d,key=lambda k: (d[k],k),reverse=True)`

预期结果是:[17,tg,61,60,59,tt,57]

enter image description here

提前谢谢

解决方法

有人帮助我找到了答案。我分享给你。

d = {'A': ['tg',17],'B': [59,60],'C': [60,61],'D': [57,'tt'],'E': [61,'tg'],'F': ['tt',59]}
 
# we build a inverted dictonnary to return the list
# the tuple of values [v1,v2] for each value v{1,2}
# {  17: [['tg',17]],#    57: [[57,'tt']],#    'tg': [['tg',[61,'tg']],#    60: [[59,[60,61]],... }
dico = dict()
for i in d.values():
    for j in i:
        dico[j] = dico.get(j,[]) + [i]
 
# we get a piece of the list,that easy there is one instance
m = min(l := [j for i in d.values() for j in i],key=l.count) # py 3.8
 
z = [m]
v1,v2 = dico[m][0]
v = v1 if v2 == m else v2 # we get the other value of the tuple
z.append(v)
 
while len(dico[v]) > 1: # until we a not a the end of the chain
    v1,v2 = [i for i in dico[v] if m not in i][0]
    m = v
    v = v1 if v2 == m else v2
    z.append(v)
 
print(z)