如何从列表创建带有整个空白键的嵌套字典?

时间:2019-09-11 17:36:21

标签: python-3.x dictionary

我知道,def show_pdf(request): template = 'show_pdf.html' myres=Research.objects.all() context = {'myres': myres} return render(request,'mainapp/show_pdf.html', context) 所使用的dict.fromkeys可以使我到达一半,但是如何调整它以达到所需的结果,例如: rt_dict = dict.fromkeys(['name', 'description', 'model'], '')

所有不带嵌套字典的键都应具有空白值。如果嵌套字典没有嵌套字典,则所有值都应为空白。

1 个答案:

答案 0 :(得分:1)

不清楚您的输入是什么样子,但这会起作用。

input = ['name', {'description': ['year', 'make']}, 'model']
result = {}
for key in input:
    if isinstance(key, dict):
        result[next(iter(key))] = dict.fromkeys(next(iter(key.values())), '')
    else:
        result[key] = ''

输出:

{'name': '', 'description': {'year': '', 'make': ''}, 'model': ''}
相关问题