Shyal Beardsley

Flatten a dictionary

Let's suppose is ths our input dictionary.

input:  dict = {
            "Key1" : "1",
            "Key2" : {
                "a" : "2",
                "b" : "3",
                "c" : {
                    "d" : "3",
                    "e" : "1"
                }
            }
        }

Then we'd need to produce this output dictionary:

output: {
            "Key1" : "1",
            "Key2.a" : "2",
            "Key2.b" : "3",
            "Key2.c.d" : "3",
            "Key2.c.e" : "1"
        }

Solution

def flatten_dictionary(dictionary):
  def flat(outk, ind):
    for k, v in ind.items():
      if type(v) == dict: 
        flat("%s.%s"%(outk, k) if outk and k else (outk or k), v)
      else:
        out[flat_key] = v
  out = {}
  flat('', dictionary)
  return out

Note that a recursive function implements this with the least amount of code. You may be tempted to write a for-loop in the outside function too, however this is not required since we can invoke the inner function with an empty key.

Array Max

Design a web crawler

Job scheduling with deadline

Binary Search

Related posts:

Post by Shyal Beardsley -- to find out more: https://shyal.com, https://ioloop.io


over 3 years ago

Shyal Beardsley