python-3.x 根据两个字典创建新字典,其中Key作为第一个字典的值,Value作为第二个字典的值

uoifb46i  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(163)

示例:

A = {1: "IWillBeAKeySoon", 7: "IHope"}
B = {1: "ItSeemsIAmAValue",6: "LostVal"}

我想把A和B结合起来得到一个像这样的法令C:

C = {"IWillBeAKeySoon": "ItSeemsIAmAValue"}

我已经手动完成:

C={A[key]:value for key,value in B.items() if key in A}

我想应该有一些内置的功能或更有效的方法来做到这一点,但我找不到它。

sdnqo3pr

sdnqo3pr1#

并行地迭代值或项将不起作用,因为键不一定匹配,也不一定以相同的顺序。
而是查找两个字典的公共键:

keys = set(A.keys()) & set(B.keys())

然后使用dict解析从每个dict中查找具有这些键的值,并将它们组装成结果的键-值对:

C = {A[k]:B[k] for k in keys}
mbskvtky

mbskvtky2#

您可以使用zip:

>>> A = {1: "IWillBeAKeySoon", 6: "MeToo"}
>>> B = {1: "ItSeemsIAmAValue",6: "Val"}
>>> C = dict(zip(A.values(), B.values()))
>>> print(c)
{'MeToo': 'Val', 'IWillBeAKeySoon': 'ItSeemsIAmAValue'}

在性能方面,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

相关问题