I'm new to python and I was trying to merge two objects into a tuple with the two elements?
I've tried like merging lists, summing them and so on, nothing worked as I wanted. The code I'm providing doesn`t works also.
def merge(dict1,dict2):
for key in dict2:
if key in dict1:
dict2[key]=dict2[key]+dict1[key]
else:
pass
return dict2
The input is this:
a = {'x': [1,2,3], 'y': 1, 'z': set([1,2,3]), 'w': 'qweqwe', 't': {'a': [1, 2]}, 'm': [1]}
And this:
b = {'x': [4,5,6], 'y': 4, 'z': set([4,2,3]), 'w': 'asdf', 't': {'a': [3, 2]}, 'm': "wer"}
And I want the output to be this:
{'x': [1,2,3,4,5,6], 'y': 5, 'z': set([1,2,3,4]), 'w': 'qweqweasdf', 't': {'a': [1, 2, 3, 2]}, 'm': ([1], "wer")}
With ^this being a single tuple.
Given there are so many types, a lot of type checking is required, but this simple recursion should work.
Also, this assumes the keys in a
and b
are the same, as they are in the example.
def merge(a,b,new_dict):
for key in a.keys():
if type(a[key]) != type(b[key]):
new_dict[key] = (a[key],b[key])
elif type(a[key]) == dict:
new_dict[key] = merge(a[key],b[key],{})
elif type(a[key]) == set:
new_dict[key] = a[key]|b[key]
else:
new_dict[key] = a[key] + b[key]
return new_dict
c = merge(a,b,{})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.