GeeTransit
GeeTransit

Reputation: 1468

Merge two dictionaries with keys only from the first dict

I want to merge two dictionaries so that the resulting dict has keys from the first dict and values from the first and second.

>>> A = {'AB': 'a', 'A': 'a'}
>>> B = {'AB': 'b', 'B': 'b'}
>>> merge_left(A, B)
{'AB': 'b', 'A': 'a'}

This is somewhat similar to a left outer join used in merging database tables in that one side is used as the "base" and the other side is compared to it.

Here is a table of what value each key should have in the resulting dict.

Possible Situations Key in A Key not in A
Key in B Use B's value Don't include
Key not in B Use A's value N/A

Is there a function merge_left or something similar that returns the dict above?

Upvotes: 1

Views: 187

Answers (1)

GeeTransit
GeeTransit

Reputation: 1468

I used dict.get's ability to return a default value to make a fairly short merge_left function. This uses a dict-comprehension over key, value pairs of the first dict and checks them against the second.

def merge_left(defaults, override):
    return {key, override.get(key, default) for key, default in defaults.items()}

Since this function is just returning a dict-comprehension, you can "inline" it directly into your code.

>>> A = {'AB': 'a', 'A': 'a'}
>>> B = {'AB': 'b', 'B': 'b'}
>>> {k: B.get(k, a) for k, a in A.items()}
{'AB': 'b', 'A': 'a'}

Upvotes: 2

Related Questions