update certain key-value pairs of a dict from another dict
Peter Otten
__peter__ at web.de
Fri Nov 11 07:29:36 EST 2016
Tim Chase wrote:
> On 2016-11-11 11:17, Daiyue Weng wrote:
>> dict1 = {'A': 'a', 'B': 'b', 'C': 'c'}
>> dict2 = {'A': 'aa', 'B': 'bb', 'C': 'cc'}
>>
>> I am wondering how to update dict1 using dict2 that
>>
>> only keys 'A' and 'B' of dict1 are udpated. It will result in
>>
>> dict1 = {'A': 'aa', 'B': 'bb', 'C': 'c'}
>
> Use dict1's .update() method:
>
>>>> dict1 = {'A': 'a', 'B': 'b', 'C': 'c'}
>>>> dict2 = {'A': 'aa', 'B': 'bb', 'C': 'cc'}
>>>> desired = {'A', 'B'}
>>>> dict1.update({k:v for k,v in dict2.items() if k in desired})
>>>> dict1
> {'C': 'c', 'B': 'bb', 'A': 'aa'}
>
>
> or do it manually
>
> for k in dict2:
> if k in desired:
> dict1[k] = dict2[k]
If desired is "small" compared to the dicts:
>>> for k in desired & dict1.keys() & dict2.keys():
... dict1[k] = dict2[k]
...
>>> dict1
{'A': 'aa', 'C': 'c', 'B': 'bb'}
The same using update(), with a generator expression that avoids the
intermediate dict:
>>> dict1 = {'A': 'a', 'B': 'b', 'C': 'c'}
>>> dict1.update((k, dict2[k]) for k in desired & dict1.keys() &
dict2.keys())
>>> dict1
{'A': 'aa', 'C': 'c', 'B': 'bb'}
As written this will add no new keys to dict1. If you want to allow new keys
use
desired & dict2.keys()
as the set of keys.
More information about the Python-list
mailing list