1

Let's say we have two dictionaries:

c1 = {'Disks': [1, 3, 6, 2], 'left': True, 'right': False}
c2 = {'Disks': [0, 5, 7, 9, 8], 'left': False, 'right': True} 

How would I add them together so that the new dictionary is as follows:

{'Disks': [1, 3, 6, 2, 0, 5, 7, 9, 8], 'left': True, 'right': True}

so basically anything in 'Disks' will merge together.

Also if one of the left keys are true the left key in the new dictionary will be true, and if both are false then the left key in the new dictionary remains false. I would also like the same thing to happen to the right key.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
DJA
  • 173
  • 6
  • Did you actually *try* something? What happened? – jonrsharpe Nov 12 '16 at 22:25
  • one of the problems i had was if i had a list and put it in my function it would eventually come out as a dictionary with true or false but if the list i input was empty than right or left may be empty depending on which one it was in....(didn't explain very well) but i think i overcame that obstacle. – DJA Nov 13 '16 at 15:58
  • Then show a [mcve] of that problem. – jonrsharpe Nov 13 '16 at 15:59

2 Answers2

3

Use a dictionary comprehension that applies a ternary operator on the values of each dict. When the values are lists, add them, otherwise use the or operator:

c = {k: v + c2[k] if isinstance(v, list) else v or c2[k] 
                                  for k, v in c1.items()}
print(c)
# {'Disks': [1, 3, 6, 2, 0, 5, 7, 9, 8], 'right': True, 'left': True}

References:

Conditional expressions

Dictionary Comprehension

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Here is one more way

>>> c1 = {'Disks':[1,3,6,2], 'left' :True, 'right': False}
>>> c2 = {'Disks' :[0,5,7,9,8], 'left':False, 'right':True }
# merge values from two dictionaries.
>>> x = zip(c1.values(), c2.values())
# Handle list types merging
>>> x = [y[0] + y[1] if type(y[0]) is list else y for y in x]
# Handle boolean types merging
>>> x = [y[0] or y[1] if type(y[0]) is bool else y for y in x]
# create the final dictionary
>>> dict(zip(c1.keys(), x))
{'Disks': [1, 3, 6, 2, 0, 5, 7, 9, 8], 'right': True, 'left': True}
Jay Rajput
  • 1,813
  • 17
  • 23