0

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)
Let'sbecool
  • 104
  • 6
  • 1
    Does this answer your question? [Find all occurrences of a key in nested dictionaries and lists](https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-dictionaries-and-lists) – ggorlen Nov 26 '21 at 17:34

1 Answers1

1

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
jhylands
  • 984
  • 8
  • 16