Alex Lenail Alex Lenail - 4 years ago 81
Python Question

How to merge pairs of dictionaries while dropping a subset of each dictionary

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 = ???

Answer Source

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}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download