向Python多维字典添加值

hec6srdp  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(183)

我有一个值,需要将它添加到多维字典中
问题是密钥可能存在,也可能不存在
如果它们存在,我只想添加它,如果不存在..我需要创建它
什么是最好的方法来做这件事,因为现在我有看起来很糟糕

if response.get('pages', {}).get(url, {}).get('variations', {}).get('custom_screenshot'):
            response['pages'][url]['variations']['custom_screenshot'][command.get('params')[0]] = output
        elif response.get('pages', {}).get(url, {}).get('variations'):
            response['pages'][url]['variations']['custom_screenshot'] = {command.get('params')[0]: output}
        elif response.get('pages', {}).get(url, {}):
            response['pages'][url]['variations'] = {'custom_screenshot': {command.get('params')[0]: output}}
        elif response.get('pages', {}):
            response['pages']['url'] = {'variations': {'custom_screenshot': {command.get('params')[0]: output}}}
        else:
            response['pages'] = {url: {'variations': {'custom_screenshot': {command.get('params')[0]: output}}}}

        return response
ddhy6vgd

ddhy6vgd1#

使用Python字典的引用性质。
1.声明应在最终响应中的中间键(按正确顺序)
1.循环调用dict.setdefaut方法的键,以设置内部字典如果它不存在
1.为自定义密钥command.get('params')[0]设置无条件值output

resp_keys = [url, 'variations', 'custom_screenshot']
pages_dict = resp.setdefault('pages', {})

for k in resp_keys:
    pages_dict = pages_dict.setdefault(k, {})  # return dict under key k
pages_dict[command.get('params')[0]] = output

相关问题