0

I have two dictionaries.


gen1 = {0: 'RR', 1: 'RR', 2: 'rR', 3: 'rR', 4: 'RR', 5: 'RR', 6: 'rR', 7: 'rR',
      8: 'Rr', 9: 'Rr', 10: 'rr', 11: 'rr', 12: 'Rr', 13: 'Rr', 14: 'rr', 15: 'rr'}


and

gen2 = {0: 'PP', 1: 'PP', 2: 'PP', 3: 'PP', 4: 'PP', 5: 'PP', 6: 'PP', 7: 'PP',
      8: 'PP', 9: 'PP', 10: 'PP', 11: 'PP', 12: 'PP', 13: 'PP', 14: 'PP', 15: 'PP'}

I want to concatenate them with same key become

gen3 = {0: 'RRPP', 1: 'RRPP', 2: 'rRPP', 3: 'rRPP', 4: 'RRPP', 5: 'RRPP', 6: 'rRPP', 7: 'rRPP',
        8: 'RrPP', 9: 'RrPP', 10: 'rrPP', 11: 'rrPP', 12: 'RrPP', 13: 'RrPP', 14: 'rrPP', 15: 'rrPP'}
xcen
  • 652
  • 2
  • 6
  • 22

4 Answers4

3

You could use a dictionary comprehension with f-strings to build a new dictionary:

{k:f'{v}{gen2.get(k, "")}' for k,v in gen1.items()}
# {k:'{}{}'.format(v, gen2.get(k, "")) for k,v in gen1.items()} # python versions under 3.6

{0: 'RRPP', 1: 'RRPP', 2: 'rRPP', 3: 'rRPP', 4: 'RRPP', 5: 'RRPP', 6: 'rRPP', 
 7: 'rRPP', 8: 'RrPP', 9: 'RrPP', 10: 'rrPP', 11: 'rrPP', 12: 'RrPP', 13: 'RrPP', 
 14: 'rrPP', 15: 'rrPP'}
yatu
  • 86,083
  • 12
  • 84
  • 139
1

A dict comprehension - slightly differently to @yatu's answer. This will operate on all unique keys from both gen1 and gen2 - if a key only exists in one of the dictionaries, the resultant dictionary will only have the value from the corresponding gen dictionary.

>>> gen1 = {0: 'RR', 1: 'RR', 2: 'rR', 3: 'rR', 4: 'RR', 5: 'RR', 6: 'rR', 7: 'rR', 8: 'Rr', 9: 'Rr', 10: 'rr', 11: 'rr', 12: 'Rr', 13: 'Rr', 14: 'rr', 15: 'rr'}
>>> gen2 = {0: 'PP', 1: 'PP', 2: 'PP', 3: 'PP', 4: 'PP', 5: 'PP', 6: 'PP', 7: 'PP', 8: 'PP', 9: 'PP', 10: 'PP', 11: 'PP', 12: 'PP', 13: 'PP', 14: 'PP', 15: 'PP'}
>>> {k: gen1.get(k, '') + gen2.get(k, '') for k in set(list(gen1.keys()) + list(gen2.keys()))}
{0: 'RRPP',
 1: 'RRPP',
 2: 'rRPP',
 3: 'rRPP',
 4: 'RRPP',
 5: 'RRPP',
 6: 'rRPP',
 7: 'rRPP',
 8: 'RrPP',
 9: 'RrPP',
 10: 'rrPP',
 11: 'rrPP',
 12: 'RrPP',
 13: 'RrPP',
 14: 'rrPP',
 15: 'rrPP'}
CDJB
  • 14,043
  • 5
  • 29
  • 55
  • 1
    One feature of this solution is that if a key is only present in one list, you'll get only the content from that list in the result. So with `gen1={0:'AA', 1:'BB'}` and `gen2={0: 'aa'}` you would get `{0: 'AAaa', 1: 'BB'}`, which might not be what you want to happen if keys are missing. – David_O Dec 11 '19 at 13:26
1

If you are sure that gen1 and gen2 have exactly the same keys, this should work:

gen3 = { k: gen1[k] + gen2[k] for k in gen1 }
Tawy
  • 579
  • 3
  • 14
1

The answer by yatu is the better solution but I thought id post another solution for the sake of curiosity.

c = {k: gen1[k] + gen2[k] for k in (gen1.keys() & gen2.keys())}

Iterates over the keys which are in both key lists.

Joshua Nixon
  • 1,379
  • 2
  • 12
  • 25