Let'sbecool
Let'sbecool

Reputation: 104

How to a key recursively in a dictionary and return it's value

I have a nested dictionary like below

dictionary = {"name": "Stephen", "language": "English", "address": "13 Aust road", "teacher_info": [{"name": "Alan", "language": "Italian"}]}

I want to return the languages.

Output = ["English", "Italian"]

What have I tried

output = []

for i, j in dictionary.items():
    if i == "language":
        output.appened(j)

Upvotes: 0

Views: 1345

Answers (1)

jhylands
jhylands

Reputation: 1014

For things like this recursion is your friend. The following function will find keys called language and add their value to the list. If any of the items in the dictionary is itself a dictionary we do the same thing. We concatenate the languages found in the nested dictionary to the list at the top level. The base case for a dictionary without any languages is an empty list.

def get_languages(dictionary):
    output = []

    for key, value in dictionary.items():
        if key == "language":
             output.appened(value)
        elif isinstance(value, dict):
            output += get_languages(value)
    return output

Upvotes: 1

Related Questions