Home > other >  Sum of two specific values in two different dicts with the same keys
Sum of two specific values in two different dicts with the same keys

Time:09-09

I am a beginner in Python and have the following problem:

I have two loops, that produce two dictionaries that look like this (of course, much longer):

dict1 = {'Manubar': ['string', 'string2', 'string3', 222, 23, 45], 'Schorsch': ['string', 'string2', 'string3', 122, 65, 44]}

dict2 = {'Manubar': ['string', 'string2', 543, 21, 34], 'Schorsch': ['string', 'string2', 354, 10, 65]}

I would now like to sum / multiply the last digits of the same key in dict1 and dict2 and create an new dict that should look like this:

dict3 = {'Manubar': ['string', 'string2', 'string3', 222, 23, **79** ], 'Schorsch': ['string', 'string2', 'string3', 122, 65, **109**]}

I tried to merge the two dicts, but that simply overwrites the values. How do I get to sum the last digits and then put them in a new dict?

CodePudding user response:

While writing this question, I came up with this:

dict3 ={}
keylist=list(dict1.keys())
xxx = 0
for _ in keylist:
    key = keylist[xxx]
    dict3.update({key: [dict1[key][5]   dict2[key][4]]})
    xxx  = 1
print(dict3)

But it feels a bit sluggish. How do I improve my code?

CodePudding user response:

An alternative:

import pandas as pd
dict1 = {'Manubar': ['string', 'string2', 'string3', 222, 23, 45], 'Schorsch': ['string', 'string2', 'string3', 122, 65, 44]}
dict2 = {'Manubar': ['string', 'string2', 543, 21, 34], 'Schorsch': ['string', 'string2', 354, 10, 65]}
df1 = pd.DataFrame.from_dict(dict1, orient='index')
df2 = pd.DataFrame.from_dict(dict2, orient='index')
df1.loc[:,5]  = df2.loc[:,4]
{i: list(v.values()) for i, v in df1.to_dict('index').items()}

CodePudding user response:

Slightly more verbose, but bit more efficient than the one-liner proposed in the comments:

dict3 = {}
for k in dict1:
    L = dict1[k].copy()
    L[-1]  = dict2[k][-1]
    dict3[k] = L

Which gives:

{'Manubar': ['string', 'string2', 'string3', 222, 23, 79], 'Schorsch': ['string', 'string2', 'string3', 122, 65, 109]}

In case curious, here are the perf comparsion results on my machine, using timeit:

long way:           0.275188707979396
comprehension way:  0.3881134579423815
  • Related