Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to merge two data structure in python

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.

like image 368
user87005 Avatar asked Feb 10 '23 18:02

user87005


1 Answers

It's quite simple:

_to.update(_from)
like image 117
ElmoVanKielmo Avatar answered Feb 12 '23 09:02

ElmoVanKielmo