Sunday, October 8, 2017

Flatten a Dictionary using python programming


Flatten a Dictionary using python programming

 
"""input:  dict = {
            "a" : "1",
            "b" : {
                "a1" : "2",
                "b1" : "3",
                "c1" : {
                    "d" : "3",
                    "e" : "1"
                }
            }
        }

output: {
            "a" : "1",
            "a.a1" : "2",
            "b.b1" : "3",
            "c.c1.d" : "3",
            "c.c1.e" : "1"
        }"""
  

def flatten_dictionary(inputdict):
  #1. create empty dictionary
  flatDictionary = {}

  flattendictionary("", inputdict, flatDictionary)
 
  return flatDictionary

def flattendictionary(initialKey, inputdict, flatDictionary):
  #2. check key to a valid dictionary
  for key, value in inputdict.iteritems():
          if not isinstance(value, type(inputdict)):
              if initialKey is None or initialKey is "":
                  flatDictionary[key] = value
              else:
                  if not key:
                    flatDictionary[initialKey] = value
                  else:
                    flatDictionary[initialKey + "." + key] = value
          else:
              if initialKey is None or initialKey is "":
                  flattendictionary(key, value, flatDictionary)
              else:
                  flattendictionary(initialKey + "." + key, value, flatDictionary)

No comments:

Post a Comment