Skip to content Skip to sidebar Skip to footer

Function That Looks Up Keys In A Dictionary Until There Is No More Associated Values

I need help creating a function that goes through a given dictionary. The value associated with that key may be another key to the dictionary. i need the function to keep looking u

Solution 1:

To extend on the other answers, which are still valid. If you have a very large dictionary then using key not in dic.keys() or k in d iterates through all keys every loop.

To go around this, one can use a try catch:

deffollow_me(dic, key):
    whileTrue:
        if key notin dic.keys():
            return key
        key = dic[key]


deffollow_me2(dic, key):
    try:
        whileTrue:
            key = dic[key]
    except Exception as e:
        return key

import time
d = { i: (i+1) for i inrange(10000000) }
start = time.time()
follow_me(d, 0)
print("Using 'in' takes", time.time() - start,"s")

start = time.time()
follow_me2(d, 0)
print("Using 'try' takes", time.time() - start,"s")

gives the output:

Using'in' takes 2.476428747177124 s
Using'try' takes 0.9100546836853027 s

Solution 2:

I think this is what you are looking for, though your problem description is very unclear:

deffollow_me(d, k):
    while k in d:
        k = d[k]
    return k

Note that the loop in this function will run forever if there is a cycle between keys and values in your dictionary. Your example has one between 'lion' and 'zebra', and it's not entirely clear how you intend such a cycle to be broken. If you want to expand each key only once, you could handle it by keeping track of the values you've seen so far in a set:

def follow_me(d, k):
    seen = set()
    while k in d and k notin seen:
        seen.add(k)
        k = d[k]
    return k

This will return whichever key in the cycle you reach first (so follow_me(d, 'zebra') with your example dictionary will return 'zebra' after going zebra => lion => zebra). If you want some other outcome, you'd need different logic and it might be tricky to do.

If you request a key that's not in the dictionary (like 'aardvark' in your example), the requested key will be returned immediately. You could add special handling for the first key you look up, but it would again make things more complicated.

Solution 3:

Considering the existence of infinite loops this has to be handled. Your description isn't clear about what should happen in this case.

def follow_me(d, key):
    visited_keys = []
    whilekeynotin visited_keys and d[key]:
        visited_keys.append(key)
        key = d[key]
    ifnot d[key]:
        returnkeyreturn"this hunt has no end"

Post a Comment for "Function That Looks Up Keys In A Dictionary Until There Is No More Associated Values"