简体   繁体   中英

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

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

A simple 5 line solution using recursion like this should work:

>>> input_dict = {"abc":{"def":{"ghi":{"jkl":{"mno":{"pqr":{"stu":{"vwx":{"yz":"you are finally here !!!"}}}}}}}}}
>>> reshaper = lambda x, y=[]: (y, x) if type(x) == str else my_func(x[list(x)[0]], y+list(x))
>>> final_list = reshaper(input_dict)
>>> final_dict = {key: final_list[0][i+1:] for i, key in enumerate(final_list[0][:-1])}
>>> final_dict.update({final_list[0][-1]: final_list[1]})
>>> final_dict
{'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 !!!'}

What this method, which I think may be one of the simplest solutions, does is it takes the dictionary and recurs through the dictionaries within dictionaries, appending each key to a list till we are left with the final string.

It then takes this list and iterates through the list to create a dictionary with values being slices with an index greater than the index of the key.

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. I somehow made it work, almost . upvote if works!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM