Home > Enterprise >  Python update dictionary value list with another dictionary
Python update dictionary value list with another dictionary

Time:10-12

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']}  

CodePudding user response:

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']}

CodePudding user response:

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']}
  • Related