0

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]}
2
  • Hint: take a look at Python’s itertools package. Commented Mar 13, 2019 at 7:17
  • 1
    @Jens Seems a bit too generic to name a package...not a very helpful comment... Commented Mar 13, 2019 at 7:21

4 Answers 4

2

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]}
Sign up to request clarification or add additional context in comments.

1 Comment

Finally something pythonic!
1

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]}

Comments

1

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

3 Comments

for key, value in b: ValueError: not enough values to unpack (expected 2, got 1)
if case is not merging the value of list a and b for matching key and code is giving error: ValueError: not enough values to unpack (expected 2, got 1)
@PradeepPandey This is technically what OP asked for and given their examples.
0

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)

1 Comment

Again, not the output OP wants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.