Home > Software design >  Add value to Python multidimensional dict
Add value to Python multidimensional dict

Time:12-11

I have a value, which I need to add it to a multidimensional dict

The problem is that the keys may or may not exist

If they exist, I just want to add it, if not .. I need to create it

What is the best way of doing this, since right now what I have looks pretty bad

        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

CodePudding user response:

Use referential nature of Python dictionary.

  1. Declare intermediate keys that should be in the final response (in proper order)
  2. Loop though the keys calling dict.setdefaut method to set the inner dictionary if it's not there
  3. Set unconditional value output for the custom key command.get('params')[0]

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
  • Related