0

guys, I have such question. Suppose that I have a dictionary/list that inside contains other dictionary/list and so on.

Example:

dict = {
'Domains':{
'Web':['JavaScript','PHP','Python'],
'Mobile':{'Android':'Java','iOS':['Swift','Objective-C'],'Windows Phone':'C#'},
'Desktop':['C#','Java','Python']}
}

And i want to find 'iOS' list in this dictionary. There is a way to call a function that will display value of an element if this element exist. Example:

print(function('iOS'))

['Swift','Objective-C']
strdr4605
  • 3,796
  • 2
  • 16
  • 26

1 Answers1

1

First, a helper function to find all dicts:

def all_dicts(a_dict):
    yield a_dict
    for key in a_dict:
        if isinstance(a_dict[key], dict):
            yield from all_dicts(a_dict[key])

And now, the lookup function:

def lookup(a_dict, key):
    for d in all_dicts(a_dict):
        if key in d:
            return d[key]

To see it in action:

>>> d = {'Domains': {'Web': ['JavaScript', 'PHP', 'Python'], 'Desktop': ['C#', 'Java', 'Python'], 'Mobile': {'Android': 'Java', 'Windows Phone': 'C#', 'iOS': ['Swift', 'Objective-C']}}}
>>> lookup(d, 'iOS')
['Swift', 'Objective-C']

If dictionaries can also exist in lists, you can adjust all_dicts to also recursively step in those.

L3viathan
  • 26,748
  • 2
  • 58
  • 81