4

I am having two complex data structure(i.e. _to and _from), I want to override the entity of _to with the same entity of _from. I have given this example.

# I am having two data structure _to and _from
# I want to override _to from _from
_to = {'host': 'test',
       'domain': [
           {
               'ssl': 0,
               'ssl_key': '',
           }
       ],
       'x': {}
       }
_from = {'status': 'on',
         'domain': [
             {
                 'ssl': 1,
                 'ssl_key': 'Xpyn4zqJEj61ChxOlz4PehMOuPMaxNnH5WUY',
                 'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq'
             }
         ]
         }
### I want this output
_result = {'host': 'test',
           'status': 'on',
           'domain': [
               {
                   'ssl': 1,
                   'ssl_key': 'Xpyn4zqJEj61ChxOlz4PehMOuPMaxNnH5WUY',
                   'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq'
               }
           ],
           'x': {}
           }

Use case 2:

_to = {'host': 'test',
       'domain': [
           {
               'ssl': 0,
               'ssl_key': '',
               'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq',
               "abc": [],
               'https': 'no'
           }
       ],
       'x': {}
       }
_from = {
         'domain': [
             {
                 'ssl': 1,
                 'ssl_key': 'Xpyn4zqJEj61ChxOlz4PehMOuPMaxNnH5WUY',
                 'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq'
             }
         ]
         }

dict.update(dict2) won't help me, because this will delete the extra keys in _to dict.

user87005
  • 964
  • 3
  • 10
  • 27

2 Answers2

7

It's quite simple:

_to.update(_from)
ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
  • @user87005 - for use case 2 (which you have added after I posted my answer), it's not clear what should happen at the list level - if the list should be merged, updated (on which criteria). – ElmoVanKielmo Jun 26 '15 at 08:03
1

There's a trap as below:

_to = {'host': 'test',
       'domain': [
           {
               'ssl': 0,
               'ssl_key': '',
           }
       ],
       'x': {}
       }
_from = {'status': 'on',
         'domain': [
             {
                 'ssl': 1,
                 'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq'
             }
         ]
         }

_to['domain']['ssl_key'] omitted when _to.update(_from) If you wanna a deep update, check Update value of a nested dictionary of varying depth

Community
  • 1
  • 1
LittleQ
  • 1,860
  • 1
  • 12
  • 14