简体   繁体   English

从两个字典创建新字典,键作为第一个字典的值,值作为第二个字典的值

[英]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:我想将 A 和 B 结合起来得到一个 dict C ,它看起来像这样:

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 :您可以使用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:关于性能, dict(zip(...)))似乎是最快的:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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