如何在一行代码中复制字典并对其进行修改 [英] How to copy a dict and modify it in one line of code

查看:62
本文介绍了如何在一行代码中复制字典并对其进行修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,我需要创建一个或两个彼此不同的字典。我通常会这样做:

Very often I need to create dicts that differ one from another by an item or two. Here is what I usually do:

setup1 = {'param1': val1, 
            'param2': val2,
            'param3': val3,
            'param4': val4,
            'paramN': valN}

setup2 = copy.deepcopy(dict(setup1))
setup2.update({'param1': val10, 
                   'param2': val20})

程序中有一个点 setup2 setup1 的副本的事实使得我很紧张,因为我担心在程序生命中的某些时候,这两行可能会分开,这对于许多错误来说是一个滑坡。

The fact that there is a point in the program at which setup2 is an identical copy of setup1 makes me nervous, as I'm afraid that at some point of the program life the two lines might get separated, which is a slippery slope towards too many bugs.

理想情况下,我希望能够在一行代码中完成此操作(类似这样):

Ideally I would like to be able to complete this action in a single line of code (something like this):

setup2 = dict(setup1).merge({'param1': val10, 
                        'param2': val20})

当然,我可以使用分号将两个命令压缩为一条物理线,但这对我来说看起来很丑。还有其他选择吗?

Of course, I can use semicolon to squeeze two commands into one physical line, but this looks pretty ugly to me. Are there other options?

推荐答案

在我看来,最简单的方法是这样的:

The simplest way in my opinion is something like this:

new_dict = {**old_dict, 'changed_val': value, **other_new_vals_as_dict}

这篇关于如何在一行代码中复制字典并对其进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆