订购一本字典以获得一系列的值

2024-04-29 04:09:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到任何解决这个问题的线索。你知道吗

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制作思维导图,这允许我跟踪节点之间的一系列关系。你知道吗


Tags: 函数字典节点关系sdk成员mydict思维
2条回答

请注意,字典是无序的,因此需要使用另一个(有序的)数据结构,例如^{}。你知道吗

实际上,在一般情况下建立联系并不容易。在您的情况下,这是可能的,因此我将提出一个解决方案,适用于您的问题类型:

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

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

docs.python.org,我的

但是,您可以将dict转换为tuple并对其进行排序:

my_sorted_tuple = sorted(my_dict.items())

相关问题 更多 >