-1

E.g I have the following

d1 = {'a': [100,300,34], 'b': [200,98,45], 'c':[450,567,300]}

d2 = {'d': [300,500,234], 'e': [300,500,234], 'f':[300,500,234]}

Want to get

d3 = {'ad': [400,800,268], 'be': [500,598,279], 'cf':[750,1067,534]}

I have the following in mind to start: for i, j in d1.items():
for x, y in d2.items():

Rich
  • 7
  • 2
  • 4
    Depending on your Python version, that may not be well defined, because the order of keys (until 3.7) is unspecified. https://stackoverflow.com/questions/5629023/the-order-of-keys-in-dictionaries – Cory Kramer Aug 20 '20 at 15:43
  • I mean in python 2.5 – Rich Aug 20 '20 at 17:38

2 Answers2

1

Here, I use a nested comprehension to achieve what you want. First, I take corresponding items in d1 and d2 using zip(). Then, I concatenate their keys, making that the key of the new dict, and use a list comprehension to sum the elements of their respective lists, which gets set as the value in the new dict.

d3 = {
        i1[0] + i2[0]: [v1 + v2 for v1,v2 in zip(i1[1], i2[1])]
        for i1,i2 in zip(d1.items(), d2.items())
    }
# {'ad': [400, 800, 268], 'be': [500, 598, 279], 'cf': [750, 1067, 534]}

Note that, before Python 3.7, the 'order' of a dict was arbitrary. Now, when you call .items(), you'll get keys in the order they were most recently added or defined, but before that you could get them in any order, and so the above would not work.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

You can do something like this:

d3 = {k1 + k2: [p + q for p, q in zip(d1[k1], d2[k2])] for k1, k2 in zip(d1.keys(), d2.keys())}

or

Without using dictionary comprehension:

d3 = {}
for k1, k2 in zip(d1.keys(), d2.keys()):
    d3[k1 + k2] = [p + q for p, q in zip(d1[k1], d2[k2])]

Output:

{'ad': [400, 800, 268], 'be': [500, 598, 279], 'cf': [750, 1067, 534]}

Make sure to use an OrderedDict if you want to maintain the order of the keys.

  • Thanks, I am actually trying to do that with for loop outside the dictionary. – Rich Aug 20 '20 at 16:06
  • How can I do that without dictionary comprehensions im using python 2.5 inside spss modeler which does nor support dict comprehensions – Rich Aug 20 '20 at 17:05