Home > Back-end >  How to extract lists and modify them from different levels of nested dictionary
How to extract lists and modify them from different levels of nested dictionary

Time:04-01

I want to extract all the lists and modify them from a nested dictionary which has multiple levels and the list can be a value in any of the levels.

For example:

test = {
    'Type 1': {
        'Type1_mainkey1': {
            'Type1_key2': {
                'Type1_key2_key1': [
                    'Type1_list1'
                ],
                'Type1_key2_key2': [
                    'Type1_list2'
                ],
                'Type1_key2_key2': [
                    'Type1_list3',
                    'Type1_list4'
                ]
            }
        }
    },

    'Type 2': {
        'Type2_mainkey1': {
            'Type2_key2': [
                'Type2_list1',
                'Type2_list2'
            ]},
            'Type2_key3': {
                'Type2_key3_key1': [
                'Type2_list3',
                'Type2_list4'
                
                ]
            }
        }
    }

This is the kind of dictionary that might be present. I was wondering if there is a way of extracting the lists and updating the dictionary.

My function so far:

def find_list(data):
    if not any([isinstance(data.get(k), dict) for k in data]):
        return data
    else:
        for dkey in data:
            if isinstance(data.get(dkey), dict):
                return find_list(data.get(dkey))
            else:
                continue

And on running this:

out = find_list(test)

My output is:

{'Type1_key2_key1': ['Type1_list1'],
 'Type1_key2_key2': ['Type1_list3', 'Type1_list4']}

Whereas, the expected output is all the list items and their keys (so that I can modify the list and update)

CodePudding user response:

In my example below the only thing I am doing differently is collecting the results during each recursive step and adding to previous returns. I added some inline comments to hopefully better explain.

def find_list(data):
    d = {}   # initialize collection object to hold results
    if not any([isinstance(data.get(k), dict) for k in data]):
        return data
    else:
        for dkey in data:
            if isinstance(data.get(dkey), dict):

                # add results of each recursive call to the collection
                d.update(find_list(data.get(dkey)))                 

    return d      # return the collection of results

Using your test dictionary with this example gives this output:

{
   'Type1_key2_key1': ['Type1_list1'], 
   'Type1_key2_key2': ['Type1_list3', 'Type1_list4'], 
   'Type2_key2': ['Type2_list1', 'Type2_list2'], 
   'Type2_key3_key1': ['Type2_list3', 'Type2_list4']
}
  • Related