gpt4 book ai didi

python - 将字典与其他字典进行比较,并仅选择其他字典中存在的那些键

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:27 27 4
gpt4 key购买 nike

我有两个字典:

union = {'a':'gamma','b':'beta','d':'theta'}
packaged = {'a':'alpha','b':'gamma','c':'alpha'}

我要:

packaged = {'a': 'alpha', 'b': 'gamma'}

因此,我只想从 packaged 中选择那些存在于 union 中的键及其值。

我读了this类似的问题,我正在做 -

for k, v in list(packaged.items()):
if k not in union.keys():
del packaged[k]
print(packaged)

这给了我想要的答案。

我的方法是最快/最有效的方法吗?如果不是,是否有更快/最有效的方法?

最佳答案

您可以使用字典理解。这将创建一个新字典,但具有与 for 循环相同的复杂性:

d = {k: v for k, v in packaged.items() if k in union}

这是一些现实的基准测试,以及两个稍微更有效的变体:

union = {'a':'gamma','b':'beta','d':'theta', **dict.fromkeys(range(5000, 10000))}
packaged = {'a':'alpha', 'b':'gamma', 'c':'alpha', **dict.fromkeys(range(1, 15000))}

def dct_cmp(union, packaged):
return {k: v for k, v in packaged.items() if k in union}

def dct_cmp_from_key(union, packaged):
return {k: packaged[k] for k in packaged if k in union}

def dct_cmp_from_key_intersect(union, packaged):
return {k: packaged[k] for k in set(packaged) & set(union)}

def loopy(union, packaged):
for k, v in list(packaged.items()):
if k not in union:
del packaged[k]
return packaged

assert dct_cmp(union, packaged.copy()) == loopy(union, packaged.copy())
assert dct_cmp(union, packaged.copy()) == dct_cmp_from_key(union, packaged.copy())
assert dct_cmp(union, packaged.copy()) == dct_cmp_from_key_intersect(union, packaged.copy())

%timeit dct_cmp(union, packaged.copy()) # 1.94 ms
%timeit dct_cmp_from_key(union, packaged.copy()) # 1.8 ms
%timeit dct_cmp_from_key_intersect(union, packaged.copy()) # 1.8 ms
%timeit loopy(union, packaged.copy()) # 2.75 ms

关于python - 将字典与其他字典进行比较,并仅选择其他字典中存在的那些键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com