update certain key-value pairs of a dict from another dict

Tim Chase python.list at tim.thechases.com
Fri Nov 11 06:59:17 EST 2016


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]

-tkc







More information about the Python-list mailing list