gpt4 book ai didi

python - 使用 iteritems 与字典查找从旧字典创建新字典的字典理解

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:49 25 4
gpt4 key购买 nike

当我有这样的想法时,我正在从一个旧的字典创建一个新的字典,我只想在键的名称上附加一个字母:

这两个 dict 理解中哪个更有效(或者更 Pythonic?)

{k: v for k, v in other_dict.iteritems()}

{k: other_dict[k] for k in other_dict}

我通常会想到第一个,但心不在焉地输入了第二个。

最佳答案

测试一下。但在实践中,除了可能非常小的字典外,iteritems 会工作得更快,仅仅是因为它避免了不必要的查找。

iteritems 绝对是更好的风格。当然,如果目标只是复制(如您的示例),那么最好的样式(和性能)就是:

other_dict.copy()

关于python - 使用 iteritems 与字典查找从旧字典创建新字典的字典理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959737/

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