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中两个字典合并