[英]print python dictionary in particular style
如何以这个给定的模式打印 Python 字典。 我在面试中被问到这个问题,我无法解决。
输入字典:
{"abc":{"def":{"ghi":{"jkl":{"mno":{"pqr":{"stu":{"vwx":{"yz":"you are finally here !!!"}}}}}}}}}
所需的 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 !!!"]}
这是一个快速的递归解决方案:
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 !!!']}
由于 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
像这样使用递归的简单 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 !!!'}
这种方法(我认为可能是最简单的解决方案之一)的作用是获取字典并在字典中的字典中递归,将每个键附加到列表中,直到我们得到最终的字符串。
然后它获取这个列表并遍历列表以创建一个字典,其中值是索引大于键索引的切片。
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)
这是一个糟糕的解决方案。 我以某种方式使它工作,几乎。 如果有效,请点赞!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.