Home > front end >  Add dictionary key-values to all keys of another dictionary
Add dictionary key-values to all keys of another dictionary

Time:04-15

I am trying to add the value of a dictionary that has only one key to all keys of another dictionary but my dictionaries have different keys. I want to do that using a loop because my original dictionary has more than 100 keys.

Here is an example of the dictionaries (dict2 should be added to each key of dict1):

dict1 = {
     'a': 3.84,
     'b': 4.9,
     'c': 6.7}


dict2={'value': {0: 1,
                 1: 6,
                 2: 10,
                 3: 2}}

For clarification, the dict2 should have only one key ('value'). The dict2 was created from a csv data frame, I tried to remove the line indexes but didn't find a way.

The "final" dictionary should have the value from dict1 and dict2 but without the "line indexes" of dict2. The final dictionary should look like this:

dict3 = {
     'a': 3.84,
           1,
           6,
           10,
           2,
     'b': 4.9,
           1,
           6,
           10,
           2,
     'c': 6.7, 
           1,
           6,
           10,
           2 }

I tried many ways to do that using append(), update() but it didn't work. I also tried to use the dict2 as an array but it didn't work too.

Thanks for any help!

CodePudding user response:

You have to make the values for each key in dict3 a list since you can't have multiple values for one key. Here is a possible solution:

dict1 = {'a': 3.84, 'b': 4.9, 'c': 6.7}
dict2 = {'value': {0: 1, 1: 6, 2: 10, 3: 2}}

def dict_merge(dict1, dict2):
    dict3 = {}
    for key in dict1:
        dict3[key] = [dict1[key]]
        for key2 in dict2["value"]:
            dict3[key].append(dict2["value"][key2])
    return dict3


print(dict_merge(dict1, dict2))

Output:

{'a': [3.84, 1, 6, 10, 2], 'b': [4.9, 1, 6, 10, 2], 'c': [6.7, 1, 6, 10, 2]}

CodePudding user response:

If you want to create a list for every dict1 key, you can use this:

dict2_values = dict2["value"].values()
dict3 = {k: [v, *dict2_values] for k, v in dict1.items()}

We used special syntax of iterable unpacking here

l1 = [1,2]
l2 = [3,4]
print([*l1, *l2, 5]) # [1,2,3,4,5]
  • Related