Python recursive functions get data from a dictionary

Python recursive functions get data from a dictionary … here is a solution to the problem.

Python recursive functions get data from a dictionary

I created a recursive function to get data from a dictionary.
A dictionary consists of keys, each of which has a list of keys before continuing. Therefore, I need to get a flattened list of keys when typing keystrokes.

My dictionary:

data = {"p": ["s1", "s2", "s3", "s4"],
        "s1": ["s1s1", "s1s2"],
        "s2": [],
        "s3": [],
        "s4": [],
        "s1s1": [],
        "s1s2": ["s1s2s1"],
        "s1s2s1": []
        }

My features:

def get_data(key):
    items = data[key]
    if items:
        for key in items:
            items += get_data(key)
    return items

When I call get_data("p") it returns

['s1', 's2', 's3', 's4', 's1s1', 's1s2', 's1s2s1', 's1s2s1']

But the expected output is:

['s1', 's2', 's3', 's4', 's1s1', 's1s2', 's1s2s1']

Thank you in advance for your help….

Solution

The problem is in these lines –

for key in items:
    items += get_data(key)

Here, you are modifying the project while you are iterating over it. So in the last iteration, your items end up getting the same key multiple times; You can add a logging statement to see which key is being used to invoke the get_data.

You want to fetch all the new items individually and update the items – when the iteration is complete

new_items = []
for key in items:
    new_items += get_data(key)
items += new_items

Related Problems and Solutions