3

Problem Statement:

I'm using python 3.5 and love the new dictionary merging syntax:

 merged = {**A, **B}

But what if you only wanted some subset of the keys in A and B?

 A_keys = [some small subset of the keys from A]
 B_keys = [some small subset of the keys from B]

 merged = ???
Alex Lenail
  • 12,992
  • 10
  • 47
  • 79

3 Answers3

1

Dictionary comprehensions to the rescue:

A = { 'one': '1', 'two': '2', 'three': '3' }
B = { 'four': '4', 'five': '5', 'six': '6' }
A_keys = ['one', 'two']
B_keys = ['five']
merged = {**{k:v for k,v in A.items() if k in A_keys}, **{k:v for k,v in B.items() if k in B_keys}}
aferber
  • 1,121
  • 10
  • 15
  • This definitely solves the problem, but isn't too elegant (effectively three dict comprehensions I think). I'll wait to see if some python master has something up their sleeve, otherwise I'll accept this one. – Alex Lenail Feb 06 '17 at 19:44
  • Well, you can do it with just two comprehensions, but you won't be using the shiny new merge syntax and it won't be as expressive: `merged = {k:v for k,v in A.items() if k in A_keys}; merged.update({k:v for k,v in B.items() if k in B_keys})` – aferber Feb 06 '17 at 20:15
0

You can combine the new notation with the answer to the question about how to select some keys from a dict:

merged = { **{ k:A[k] for k in A.keys() & A_keys }, **{ k:B[k] for k in B.keys() & B_keys }}

This works even if some values in A_keys or B_keys are not really keys in A or B.

Community
  • 1
  • 1
fjarino
  • 191
  • 4
-1

You can access by calling specific keys which you want to merge from both the sets.

  dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
  dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}

Merge the desired keys

print (dict1['bookA'] + dict2['bookB'])

Result:

{'bookE': 5, 'bookD': 4, 'bookB': 2, 'bookA': 1, 'bookC': 3}

or you can store the result to new dictonary.

y = dict1['bookA'] + dict2['bookB']

print (y)
Ramineni Ravi Teja
  • 3,568
  • 26
  • 37