从字典中找到最长路径的键

find the key with longest path from the dictionary

从字典中找到最长路径的键。键值对将是整数。考虑以下字典 d={2:1,3:2,4:5,1:4} 这里第一个键是 2,它的值是 1。所以你需要找到键 1 的值。这个方法必须遵循,直到字典中不存在该值作为键或者该值成为我们开始的键遍历字典

我这样试过:

    d = {2: 1, 3: 2, 4: 5, 1: 4}
    k = 0
    count = 0


    def find(k):
      m = d[k]
      return m


    for i in d.keys():
          k = d[i]
          find(k)
    count = count + 1
    print(count)

我的目标是将 each 传递给函数并且 return

如果我是对的,这就是您需要的功能:

d = {2:1, 3:2, 4:5, 1:4}

所以如果
键 = 2,值 = 1;
键 = 1,值 = 4;
键 = 4,值 = 5;
key = 5 --> 没有值所以到此为止

从而找到最长路径的key:

d={2:1,3:2,4:5,1:4}
c1=0
ans_key = -1
for i in d.keys():
    k=i
    c=0
    while(k in d.keys()):
        k = d[k]
        c+=1
    if(c1<c):
        c1=c
        ans_key=i
print("The Key with the longest path is",ans_key)

这将 return 输出:

The Key with the longest path is 3

希望对您有所帮助!