Skip to content
Advertisement

print python dictionary in particular style

How to print a Python dictionary in this given pattern. I was asked this question in an interview and I couldn’t solve it.

Input dictionary:

{"abc":{"def":{"ghi":{"jkl":{"mno":{"pqr":{"stu":{"vwx":{"yz":"you are finally here !!!"}}}}}}}}}

Desired output:

{"abc":["def","ghi","jkl","mno","pqr","stu","vwx","yz"],
 "def":["ghi","jkl","mno","pqr","stu","vwx","yz"],
 "ghi":["jkl","mno","pqr","stu","vwx","yz"],
 "jkl":["mno","pqr","stu","vwx","yz"],
 "mno":["pqr","stu","vwx","yz"],
 "pqr":["stu","vwx","yz"],
 "stu":["vwx","yz"],
 "vwx":["yz"],
 "yz":["you are finally here !!!"]}

Advertisement

Answer

Here’s a quick recursive solution:

from pprint import pprint

data = {"abc":{"def":{"ghi":{"jkl":{"mno":{"pqr":{"stu":{"vwx":{"yz":"you are finally here !!!"}}}}}}}}}

def a_particular_style(data):
    ret = {}
    for k, v in data.items():
        if isinstance(v, dict):
            d = a_particular_style(v)
            ret.update(d)
            ret[k] = list(reversed(d))
        else:
            ret[k] = [v]
    return ret

pprint(a_particular_style(data))
{'abc': ['def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz'],
 'def': ['ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz'],
 'ghi': ['jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz'],
 'jkl': ['mno', 'pqr', 'stu', 'vwx', 'yz'],
 'mno': ['pqr', 'stu', 'vwx', 'yz'],
 'pqr': ['stu', 'vwx', 'yz'],
 'stu': ['vwx', 'yz'],
 'vwx': ['yz'],
 'yz': ['you are finally here !!!']}

Since each “level” of the dict is built from the next level down, it’s easier to visualize how this works if you start at the bottom with the smallest dict:

print(a_particular_style({"yz":"you are finally here !!!"}))
# {'yz': ['you are finally here !!!']}

print(a_particular_style({"vwx":{"yz":"you are finally here !!!"}}))
# {'vwx': ['yz'], 'yz': ['you are finally here !!!']}    

print(a_particular_style({"stu":{"vwx":{"yz":"you are finally here !!!"}}}))
# {'stu': ['vwx', 'yz'], 'vwx': ['yz'], 'yz': ['you are finally here !!!']}

# etc
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement