Python 订购字典以获得一系列值
我找不到解决这个问题的任何线索 SDK中的函数生成的字典如下所示:Python 订购字典以获得一系列值,python,dictionary,Python,Dictionary,我找不到解决这个问题的任何线索 SDK中的函数生成的字典如下所示: myDict = {('c3','4'):20,('1','2a'):5,('4','5'):1,('2a','c3'):8} 我希望能够订购字典以获取: myDict = {('1','2a'):5, ('2a','c3'):8, ('c3','4'):20, ('4','5'):1} 其中,以下键元组的第一个成员与前一个键元组的第二个成员相同 我正在使用Xmind制作思维导图,这使我能够跟踪节点之间的一系列关系 最好将字
myDict = {('c3','4'):20,('1','2a'):5,('4','5'):1,('2a','c3'):8}
我希望能够订购字典以获取:
myDict = {('1','2a'):5, ('2a','c3'):8, ('c3','4'):20, ('4','5'):1}
其中,以下键元组的第一个成员与前一个键元组的第二个成员相同
我正在使用Xmind制作思维导图,这使我能够跟踪节点之间的一系列关系
最好将字典视为键:值对的无序集,要求键是唯一的(在一个字典内)
,强调我的
但是,您可以将dict
转换为tuple
,并对其进行排序:
my_sorted_tuple = sorted(my_dict.items())
请注意,字典是无序的,因此需要使用另一个(有序的)数据结构,例如 实际上,在一般情况下建立连接并不容易。在您的情况下,这是可能的,因此我将提供一种适用于您的问题类型的解决方案:
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)])
字典无序,无法排序。