Home > Back-end >  print python dictionary in particular style
print python dictionary in particular style

Time:09-11

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 !!!"]}

CodePudding user response:

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

CodePudding user response:

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

d = {}
loop = True
while loop:
    for i in a:
        if i == 'yz':
            loop = False
        d[i] = []
        a = a[i]

for i in d:
    pos = list(d.keys())
    d[i] = pos[pos.index(i)   1:]
print(d)

Here is a bad solution

  • Related