Finding the overlap between two dictionary keys and creating a new dictionary from both of the dict values

Viewed 78

I have two dictionaries as follows:

a = {XX: 1000, YY: 2000}
b = {XX: 'foo', YY: 'bar'}

and I would like to match the keys of a and b to output a dictionary in the form:

c = {'foo': 1000, 'bar': 2000}

I know I can create a set with just the matched keys:

set(a.keys()) & set(b.keys())

but this doesn't keep the data relations I want together. I feel like I'm overcomplicating something that has a simple Pythonic way to be done.

2 Answers

One way using intersection of dict.keys:

{b[k]: a[k] for k in a.keys() & b.keys()}

Output:

{'foo': 1000, 'bar': 2000}

You can make use of zip:

a = {"XX": 1000, "YY": 2000}
b = {"XX": 'foo', "YY": 'bar'}

print(dict(zip(b.values(), a.values())))

Out:

{'foo': 1000, 'bar': 2000}
Related