2

How can I print a dictionary as a union of given dictionaries & appending the values if the keys are equal?

Input:

dict_1 = {
    "x":[1,"hello"],
    "y":[2,"world"],
    "z":3
}

dict_2 ={
    "p":4,
    "q":19,
    "z":123
}

Output:

dict_3={"x":[1,"hello"],
    "y":[2,"world"],
    "z":[3,123],
    "p":4,
    "q":19,
        }
cottontail
  • 10,268
  • 18
  • 50
  • 51

2 Answers2

2

Try this: Check out the inline comments for explanation of what is happening.

for key,value in dict1.items():  # loop through dict1
    if key in dict2:             # see if each key in dict1 exists in dict2
        if isinstance(dict2[key], list):  # if it is in dict2 check if the value is a list.
            dict2[key].append(value)  # if it is a list append the dict1 value
        else:  # otherwise
            dict2[key] = [dict2[key], value]  # create a new list and stick 
                                              # the values for dict1 and 
                                              # dict2 inside of it
    else:  # if the key is not in dict2
        dict2[key] = value  # set the new key and value in dict2

print(dict2) # output

if you want to check for other collections try this


for key,value in dict1.items():  # loop through dict1
    if key in dict2:             # see if each key in dict1 exists in dict2
        if hasattr(dict2[key], '__iter__'):  # if it is in dict2 check if the value is a list.
           if value not in dict2[key]:
               try:
                   dict2[key].append(value)
               except:
                   dict2[key].add(value)
               finally:
                   dict2[key] = tuple(list(dict2[key]) + [value])         
        else:  # otherwise
            dict2[key] = [dict2[key], value]  # create a new list and stick 
                                              # the values for dict1 and 
                                              # dict2 inside of it
    else:  # if the key is not in dict2
        dict2[key] = value  # set the new key and value in dict2

print(dict2) # output
Alexander
  • 16,091
  • 5
  • 13
  • 29
2

Try this

# use the union of the keys and construct a list if a key exists in both dicts
# otherwise get the value of the key from the dict it exists in
{k:[dict_1[k], dict_2[k]] if all(k in d for d in [dict_1, dict_2]) else (dict_1.get(k) or dict_2.get(k)) for k in set(dict_1).union(dict_2)}
# {'x': [1, 'hello'], 'q': 19, 'y': [2, 'world'], 'z': [3, 123], 'p': 4}

This can be written (hopefully) a little more readably by using next and walrus operator:

{k: next(i for i in v if i is not None) if None in (v:=[dict_1.get(k), dict_2.get(k)]) else v for k in set(dict_1).union(dict_2)}

The same code as a normal loop:

dict_3 = {}
# loop over the union of the keys
for k in set(dict_1).union(dict_2):
    # construct the list from the values 
    v = [dict_1.get(k), dict_2.get(k)]
    # if a key doesn't exist in one of the dicts, it will dict.get() will give None
    if None in v:
        # in which case, get the non-None value
        dict_3[k] = next(i for i in v if i is not None)
   # otherwise, i.e. a key exists in both dicts,
    else:
        dict_3[k] = v
cottontail
  • 10,268
  • 18
  • 50
  • 51