0

I have the following nested dict. How can I extract in a list all the values of key '_type'? I tried to:

for e in d.values():
    print (e['_type'])

However, I am getting a TypeError: string indices must be integers. In this cases which should be the correct way of extracting all the possible values that can take _type?

anon
  • 836
  • 2
  • 9
  • 25

3 Answers3

3

Extracting all values of key _type into a list (using recursion):

def extract_keys(d):
    if isinstance(d, dict):
        for k, v in d.items():
            if k=='_type':
                yield v
            else:
                yield from extract_keys(v)
    elif isinstance(d, list):
        for v in d:
            yield from extract_keys(v)

out = list(extract_keys(d)) # variable `d` is your dict from your question

print(out)

Prints:

['FunctionDef', 'arguments', 'arg', 'Expr', 'Str', 'Assign', 'Name', 'Store', 'Num', 'For', 'Assign', 'Name', 'Store', 'BinOp', 'BinOp', 'BinOp', 'Name', 'Load', 'BitXor', 'Call', 'Name', 'Load', 'Name', 'Load', 'Add', 'BinOp', 'BinOp', 'Name', 'Load', 'RShift', 'Num', 'Add', 'BinOp', 'Name', 'Load', 'LShift', 'Num', 'BitAnd', 'Num', 'Name', 'Load', 'Name', 'Store', 'Return', 'Name', 'Load']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • @anon There are various question here on SO, for example https://stackoverflow.com/questions/3860813/recursively-traverse-multidimensional-dictionary-dimension-unknown – Andrej Kesely Jul 30 '19 at 05:50
1

you can find any data from nested dictionary using key :

def findDataFromNestedDict(nestedDict, dict_keys):
    if dict_keys in nestedDict.keys():
        return nestedDict[dict_keys]
    for key, value in nestedDict.items():
        if isinstance(value, dict):
            return  findDataFromNestedDict(value,dict_keys)

data =  findDataFromNestedDict(yourDictionary, yourKey)
SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14
-2

Supposing that you dic is something like:

dic = {'hi':[1,2,3], 'hello': [4,5,6]}

And that you want to get 1, 2, 3 from [1,2,3], do this:

for e in dic['hi']:
    print(e)