简体   繁体   English

以特定样式打印 python 字典

[英]print python dictionary in particular style

How to print a Python dictionary in this given pattern.如何以这个给定的模式打印 Python 字典。 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:所需的 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:由于 dict 的每个“级别”都是从下一个级别构建的,因此如果从最小的 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:像这样使用递归的简单 5 行解决方案应该可以工作:

>>> 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!!如果有效,请点赞!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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