Adding a Key-Value pair in a list in an empty dictionary if the keys are the same

Advertisements

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,
        }

>Solution :

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

Leave a ReplyCancel reply