简体   繁体   中英

Python update dictionary value list with another dictionary

I have the following dictionary:

dict1 = {'key1': ['val1', 'val2', 'val3'], 'key2': ['val3', 'val4']}
dict2 = {'val1': ['a', 'b'], 'val3': ['c', 'd']}

How do I update the values in dict1 from dict2 to get the following updated dict1 ?

{'key1': ['a', 'b', 'val2', 'c', 'd'], 'key2': ['c', 'd', 'val4']}  

You may loop over every pair of first dict and replace each value by the list pointed in dict2 if exists, else keep the value. That can be done nicely with dict.get , that will return the list of new values to use or [value] which is the actual value

dict1 = {'key1': ['val1', 'val2', 'val3'], 'key2': ['val3', 'val4']}
dict2 = {'val1': ['a', 'b'], 'val3': ['c', 'd']}

for key, values in dict1.items():
    new_values = []
    for value in values:
        new_values.extend(dict2.get(value, [value]))
    dict1[key] = new_values

print(dict1)  # {'key1': ['a', 'b', 'val2', 'c', 'd'], 'key2': ['c', 'd', 'val4']}

You could use nested comprehensions:

dict1 = {'key1': ['val1', 'val2', 'val3'], 'key2': ['val3', 'val4']}
dict2 = {'val1': ['a', 'b'], 'val3': ['c', 'd']}

dict1 = { k1:[v2 for v1 in values1 for v2 in dict2.get(v1,[v1])] 
          for k1,values1 in dict1.items()}

print(dict1)
{'key1': ['a', 'b', 'val2', 'c', 'd'], 'key2': ['c', 'd', 'val4']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM