简体   繁体   中英

merge two dictionaries with same key values

I have two dictionaries which consist same keys

a = {'a':[3,2,5],
     'b':[9,8],
     'c':[1,6]}

b = {'b':[7,4],
     'c':[10,11]}

When i merge them the keys of dictionary b replaces the keys of a because of the same name. Here's the merge code I am using

z = dict(list(a.items()) + list(b.items()))

Is there somehow I can keep all the keys, I know dictionaries can't have same key name but I can work with something like this:

a = {'a':[3,2,5],
     'b':[9,8],
     'c':[1,6],
     'b_1':[7,4],
     'c_1':[10,11]}

You can use a generator expression inside the method update() :

a.update((k + '_1' if k in a else k, v) for k, v in b.items())
# {'a': [3, 2, 5], 'b': [9, 8], 'c': [1, 6], 'b_1': [7, 4], 'c_1': [10, 11]}

While I think Usman's answer is probably the "right" solution, technically you asked for this:

for key, value in b.items():
  if key in a:
    a[key + "_1"] = value
  else:
    a[key] = value

Do something like this perhaps:

a = {'a':[3,2,5],
     'b':[9,8],
     'c':[1,6]}

b = {'b':[7,4],
     'c':[10,11]}

z = {}

for key in a:
    if key in b:
        z[key + "_1"] = b[key]
        z[key] = a[key]
    else:
        z[key] = a[key]


print(z)                            

Output:

{'a': [3, 2, 5], 'b_1': [7, 4], 'b': [9, 8], 'c_1': [10, 11], 'c': [1, 6]}

Check if key of b present in a then add in a with key_1 value of b for key other wise add in key in a the value of b for key.

a = {'a':[3,2,5],
     'b':[9,8],
     'c':[1,6]}

b = {'b':[7,4],
     'c':[10,11]}
for k in b:
    if k in a:
        a[k+'_1']=b[k]
    else:
        a[k]=b[k]
print(a)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM