python中两个字典合并_在Python中的一个表达式中合并两个字典

python中两个字典合并

Until version less than 3.4, in python, it was quite a task (no single line approach available) to merge two dictionaries in a single expression. For instance, in version less than 3.4 we had to do something similar (as below) to merge two dictionaries.

在python小于3.4的版本中, 将两个字典合并到一个表达式中是一项艰巨的任务(没有可用的单行方法)。 例如,在小于3.4的版本中,我们必须执行类似的操作(如下所示)以合并两个字典

def merge(dict_1, dict_2):
    z = dict_1.copy()   
    z.update(dict_2)    
    return z
    
if __name__ == "__main__":
    dict_1 = {'x':1, 'y':2}
    dict_2 = {'a':3, 'b':4}
    merged_dict = merge(dict_1, dict_2)
    print(merged_dict)

Output

输出量

{'x': 1, 'y': 2, 'a': 3, 'b': 4}

In the above example, (ref merge method), the dict_1 is shallow copied to a different variable called z, and the z is then updated with the values of dict_2, which results in the merging of two dictionaries.

在上面的示例(参考合并方法)中,将dict_1浅复制到另一个名为z的变量,然后用dict_2的值更新z ,这将导致两个字典合并

在一行中合并两个字典 (Merge two dictionaries in a single line)

With python 3.5+, the below approach is generally followed to merge two (or more) dictionaries.

在python 3.5+中,通常遵循以下方法来合并两个(或多个)字典

if __name__ == "__main__":
    dict_1 = {'x':1, 'y':2}
    dict_2 = {'a':3, 'b':4}
    merged_dict = {**dict_1, **dict_2}
    print(merged_dict)

Output

输出量

{'x': 1, 'y': 2, 'a': 3, 'b': 4}

The above can be used to merge two or more dictionaries, like below,

上面的代码可用于合并两个或多个字典 ,如下所示,

if __name__ == "__main__":
    dict_1 = {'x':1, 'y':2}
    dict_2 = {'a':3, 'b':4}
    dict_3 = {'p':5, 'q':6}
    merged_dict = {**dict_1, **dict_2, **dict_3}
    print(merged_dict)

However, since most of the organizations have not yet moved to the latest version of Python, the general approach followed is as mentioned in the initial example.

但是,由于大多数组织尚未迁移到最新版本的Python,因此遵循的一般方法如初始示例中所述。

翻译自: https://www.includehelp.com/python/merge-two-dictionaries-in-a-single-expression.aspx

python中两个字典合并

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值