how to assign value in dict1 to dict2 if the key are the same without loop

Viewed 25

Now I have two dicts, and one is a template(values are empty). Now I want to assign values in dict2 to dict1 if the key in two dicts is the same. But without using loop(better not access in two dicts). Just operate in the dictionary layer. the two dicts are like:

dict1:                                           dict2:               
{                                                {
    "indexed": true,                                 "name": "_target",
    "internalType": "",                              "type": "address",
    "name": "",                                      "result": "0xED3A954c0ADFC8"
    "type": "",                                  }
    "result": ""
}
in the last I wanna get:
{                                                
    "indexed": true,                  
    "internalType": "",                  
    "name": "_target",                      
    "type": "address",              
    "result": "0xED3A954c0ADFC8"
}
without access in two dict(no loop)

In my opinion, this could use set to manipulate it, but I can't manage to do it.

1 Answers

Possible solutions are the following:

dict1 = {"indexed": True, "internalType": "", "name": "", "type": "", "result": ""}
dict2 = {"name": "_target", "type": "address", "result": "0xED3A954c0ADFC8"}

Python 3.9+:

dict_3 = dict1 | dict2

Python 3.5+:

dict_3 = {**dict1, **dict2}

Prints

print(dict_3)

{'indexed': True,
 'internalType': '',
 'name': '_target',
 'type': 'address',
 'result': '0xED3A954c0ADFC8'}
Related