<p>请注意,字典是无序的,因此需要使用另一个(有序的)数据结构,例如<a href="https://docs.python.org/library/collections.html#collections.OrderedDict" rel="nofollow noreferrer">^{<cd1>}</a>。你知道吗</p>
<p>实际上,在一般情况下建立联系并不容易。在您的情况下,这是可能的,因此我将提出一个解决方案,适用于您的问题类型:</p>
<pre><code>inp = {('c3', '4'): 20,
('1', '2a'): 5,
('4', '5'): 1,
('2a', 'c3'): 8}
# Collect the start and end points
starts = {}
ends = {}
for key in inp:
start, end = key
starts[start] = key
ends[end] = key
print(starts)
# {'1': ('1', '2a'), '2a': ('2a', 'c3'), '4': ('4', '5'), 'c3': ('c3', '4')}
print(ends)
# {'2a': ('1', '2a'), '4': ('c3', '4'), '5': ('4', '5'), 'c3': ('2a', 'c3')}
# Find the ultimate start point - that's the tricky step in general,
# but it's easy in your case.
startpoint = set(starts).difference(ends)
startpoint = next(iter(startpoint)) # yeah, it's a bit ugly to get the one and only item of a set...
print(startpoint)
# '1'
# Find the connections
from collections import OrderedDict
res = OrderedDict()
while startpoint in starts:
tup = starts[startpoint]
res[tup] = inp[tup]
startpoint = tup[1] # next start point
print(res)
# OrderedDict([(('1', '2a'), 5), (('2a', 'c3'), 8), (('c3', '4'), 20), (('4', '5'), 1)])
</code></pre>