user21138479
user21138479

Reputation: 11

Combining dictionaries in Python

I am trying to combine the following dictionaries into the ideal output and am not sure how it is done.

day1 = {'Sci': [21.0],'Math': [16.0]}
day2 = {'Sci': [11.1],'Math': [16.1]}

Expected output:

{'Sci': [21.0, 11.1],'Math': [16.0, 16.1]}

How can I go about it?

Upvotes: 0

Views: 106

Answers (3)

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11612

In these cases, I like to create a generic function to simplify the task at hand.

Here is a helper function which accepts any number of input dict objects to merge the K/V pairs of:

Note: this assumes that all values in an input dict object are of type list.

def merge(*dicts):
    res = {}
    for d in dicts:
        for k in d:
            if cur_list := res.get(k):
                cur_list += d[k]
            else:
                cur_list = d[k]
            res[k] = cur_list
    return res

Now, calling the function via:

day1 = {'Sci': [21.0],'Math': [16.0]}
day2 = {'Sci': [11.1],'Math': [16.1]}

print(merge(day1, day2))

Result:

{'Sci': [21.0, 11.1], 'Math': [16.0, 16.1]}

Upvotes: 0

B Remmelzwaal
B Remmelzwaal

Reputation: 1629

You can use dictionary comprehension:

day1 = {'Sci': [21.0],'Math': [16.0]}
day2 = {'Sci': [11.1],'Math': [16.1]}

output = {key: d1 + d2 for (key, d1), d2 in zip(day1.items(), day2.values())}

print(output)

Output:

{'Sci': [21.0, 11.1], 'Math': [16.0, 16.1]}

Assuming day1 has the same keys as day2.

Edit: if we are going to assume that, the previous method is way overcomplicated. This suffises:

output = {k: day1[k] + day2[k] for k in day1}

Upvotes: 1

Aleksa Majkic
Aleksa Majkic

Reputation: 803

Based on the question, here is my attempt at solving your problem. Please keep in mind this only works if both of your dictionaries have the same keys.

day1 = {'Sci': [21.0],'Math': [16.0]}
day2 = {'Sci': [11.1],'Math': [16.1]}

output = {}
for key in day1:
    output[key] = day1[key] + day2[key]

print(output)

The code above will give you the following output:

{'Sci': [21.0, 11.1], 'Math': [16.0, 16.1]}

Upvotes: 0

Related Questions