Python | Convert nested dictionary into flattened dictionary

Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by ‘_’ in case of the nested key to be started.

Given below are a few methods to solve the above task.

Method #1: Using Naive Approach



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# conversion of nested dictionary
# into flattened dictionary
  
# code to convert ini_dict to flattened dictionary
# default seperater '_'
def flatten_dict(dd, separator ='_', prefix =''):
    return { prefix + separator + k if prefix else k : v
             for kk, vv in dd.items()
             for k, v in flatten_dict(vv, separator, kk).items()
             } if isinstance(dd, dict) else { prefix : dd }
          
# initialising_dictionary
ini_dict = {'geeks': {'Geeks': {'for': 7}},
            'for': {'geeks': {'Geeks': 3}},
            'Geeks': {'for': {'for': 1, 'geeks': 4}}}
  
# priniting initial dictionary
print ("initial_dictionary", str(ini_dict))
  
  
# printing final dictionary
print ("final_dictionary", str(flatten_dict(ini_dict)))

chevron_right


Output:

initial_dictionary {‘geeks’: {‘Geeks’: {‘for’: 7}}, ‘Geeks’: {‘for’: {‘geeks’: 4, ‘for’: 1}}, ‘for’: {‘geeks’: {‘Geeks’: 3}}}
final_dictionary {‘Geeks_for_for’: 1, ‘geeks_Geeks_for’: 7, ‘for_geeks_Geeks’: 3, ‘Geeks_for_geeks’: 4}

 
Method #2: Using mutuableMapping

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# conversion of nested dictionary
# into flattened dictionary
  
from collections import MutableMapping
  
# code to convert ini_dict to flattened dictionary
# default seperater '_'
def convert_flatten(d, parent_key ='', sep ='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
  
        if isinstance(v, MutableMapping):
            items.extend(convert_flatten(v, new_key, sep = sep).items())
        else:
            items.append((new_key, v))
    return dict(items)
          
# initialising_dictionary
ini_dict = {'geeks': {'Geeks': {'for': 7}},
            'for': {'geeks': {'Geeks': 3}},
            'Geeks': {'for': {'for': 1, 'geeks': 4}}}
  
# priniting initial dictionary
print ("initial_dictionary", str(ini_dict))
  
  
# printing final dictionary
print ("final_dictionary", str(convert_flatten(ini_dict)))

chevron_right


Output:

initial_dictionary {‘Geeks’: {‘for’: {‘for’: 1, ‘geeks’: 4}}, ‘for’: {‘geeks’: {‘Geeks’: 3}}, ‘geeks’: {‘Geeks’: {‘for’: 7}}}
final_dictionary {‘Geeks_for_geeks’: 4, ‘for_geeks_Geeks’: 3, ‘geeks_Geeks_for’: 7, ‘Geeks_for_for’: 1}

 
Method #3: Using Python Generators

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# conversion of nested dictionary
# into flattened dictionary
  
def flattenit(pyobj, keystring =''):
   if type(pyobj) is dict:
     if (type(pyobj) is dict):
         keystring = keystring + "_" if keystring else keystring
         for k in pyobj:
             yield from flattenit(pyobj[k], keystring + k)
  
     elif (type(pyobj) is list):
         for lelm in pyobj:
             yield from flatten(lelm, keystring)
   else:
      yield keystring, pyobj
          
# initialising_dictionary
ini_dict = {'geeks': {'Geeks': {'for': 7}},
            'for': {'geeks': {'Geeks': 3}},
            'Geeks': {'for': {'for': 1, 'geeks': 4}}}
  
# priniting initial dictionary
print ("initial_dictionary", str(ini_dict))
  
# code to convert ini_dict to flattened dictionary
res = {k:v for k, v in flattenit(ini_dict)}
  
# printing final dictionary
print ("final_dictionary", str(res))

chevron_right


Output:

initial_dictionary {‘for’: {‘geeks’: {‘Geeks’: 3}}, ‘geeks’: {‘Geeks’: {‘for’: 7}}, ‘Geeks’: {‘for’: {‘for’: 1, ‘geeks’: 4}}}
final_dictionary {‘Geeks_for_geeks’: 4, ‘for_geeks_Geeks’: 3, ‘Geeks_for_for’: 1, ‘geeks_Geeks_for’: 7}




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.