0

I have this:

dict1 = {"a":3, 'b':4}
dict2 = {"a":6, 'b':5}

I need to get to this:

target_dict = {"a":[3,6], 'b':[4,5]}

I tried and it doesn't work.

from collections import defaultdict
target_dict  = defaultdict(list)
dict1 = {"a": [3], 'b':[4]}
dict2 = {"a": [6], 'b':[5]}
target_dict.append(dict1)
target_dict.append(dict2)
target_dict

Please help.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
BEN
  • 63
  • 6

2 Answers2

1

Try this

from collections import defaultdict

dict1 = {"a": 3, 'b': 4}
dict2 = {"a": 6, 'b': 5}

target_dict = defaultdict(list)
for dictionary in [dict1, dict2]:
    for k, v in dictionary.items():
        target_dict[k].append(v)
Fu Hanxi
  • 186
  • 1
  • 15
0

Maybe this help:

dict1 = {"a":3, 'b':4}
dict2 = {"a":6, 'b':5}

def combine(dict1,dict2):
    new_dict = {}
    for name in dict1.keys():
        new_dict[name]=[dict1[name],dict2[name]]
    return new_dict

And the result is {'a': [3, 6], 'b': [4, 5]}

CuCaRot
  • 1,208
  • 7
  • 23