-4

I tried to find a solution. Perhaps my words are bad chosen. Sorry for my english.

I have a dictionary.

  • Each key has two values
  • all the keys have common values, except for two.
  • you'll understand, it's a chain. Now, I know I can't order a dictionary, so I'd like to know, if it's possible to arrange - in a list - the values. I've found something that comes close, but it still doesn't work.

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)`

the expected result is that: [17,tg,61,60,59,tt,57]

enter image description here

by advance thank you

  • 1
    Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to implement this feature” is not a Stack Overflow issue. You have to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. This is a straightforward problem in graph traversal. Please research basic graph representation (you have a nice collection of edges and nodes already), and basic algorithms. – Prune Aug 11 '20 at 21:34
  • 2
    This is a linked list. Use a linked list for this. – Peri Aug 11 '20 at 21:34
  • hi Prune. If I ask the question, it's because - while searching - in the other topics, I didn't find the answer. what seems simple to you isn't necessarily simple to everyone. I just wanted help. if you're only helping the experts, excuse me for using the wrong site. – maxime neko Aug 11 '20 at 21:43
  • thank you Flutterish for this information. now I know where to search. – maxime neko Aug 11 '20 at 21:56

1 Answers1

0

Someone helped me to find the answer. I share you this.

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', 17], [61, 'tg']],
#    60: [[59, 60], [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)