Reputation: 2468
Example:
A = {1: "IWillBeAKeySoon", 7: "IHope"}
B = {1: "ItSeemsIAmAValue",6: "LostVal"}
I would like to combine A and B to get a dict C that looks like this:
C = {"IWillBeAKeySoon": "ItSeemsIAmAValue"}
I have done it manually:
C={A[key]:value for key,value in B.items() if key in A}
I think there should be some built-in functions or more efficient way to do it, but I can't find it.
Upvotes: 1
Views: 795
Reputation: 61654
Iterating over either the values or items in parallel will not work because the keys are not necessarily matching and also not necessarily in the same order.
Instead, find keys common to both dictionaries:
keys = set(A.keys()) & set(B.keys())
Then use a dict comprehension to look up the values from each dict with those keys, and assemble them into key-value pairs for the result:
C = {A[k]:B[k] for k in keys}
Upvotes: 2
Reputation: 18136
You could make use of zip:
>>> A = {1: "IWillBeAKeySoon", 6: "MeToo"}
>>> B = {1: "ItSeemsIAmAValue",6: "Val"}
>>> C = dict(zip(A.values(), B.values()))
>>> print(c)
{'MeToo': 'Val', 'IWillBeAKeySoon': 'ItSeemsIAmAValue'}
Regarding performance, dict(zip(...)))
seems to be the fastest:
import timeit
A = {x: '%s%12d' % ('a', x) for x in range(100)}
B = {x: '%s%12d' % ('b', x) for x in range(100)}
def v1():
C={A[key]:value for key,value in B.items() if key in B}
def v2():
C = dict(zip(A.values(), B.values()))
def v3():
C = {x[0]: x[1] for x in zip(A.values(), B.values())}
print(timeit.timeit(v1))
print(timeit.timeit(v2))
print(timeit.timeit(v3))
18.561055098
9.385801745000002
17.763003313
Upvotes: -1