简体   繁体   中英

Creating New dictionary from two dictionaries with Key as First dict's Value, and Value as the second dict's Value

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM