Search code examples
pythondictionarykeyreturn-value

find the key with longest path from the dictionary


find the key with longest path from the dictionary. The key value pair will be integers. consider the following dictionary d={2:1,3:2,4:5,1:4} here the first key is 2 and its value is 1. so you need to find the value of key 1. this method has to follow until the value is not present in the dictionary as a key or the value become the key where we start to traverse the dictionary

i tried like this :

    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)

my aim pass the each to function and return


Solution

  • If I'm right, this is the functionality you require:

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

    so if
    key = 2, value = 1;
    key = 1, value = 4;
    key = 4, value = 5;
    key = 5 --> No value so stop here

    Thus to find the key with the longest path:

    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)
    

    This will return the output:

    The Key with the longest path is 3

    Hope this helps!