美文网首页python
python合并字典

python合并字典

作者: wit92 | 来源:发表于2020-06-13 00:04 被阅读0次

Python 中两个字典(dict)合并Python 中两个字典(dict)合并

dict1 = { "name":"owen", "age": 18 }
dict2 = { "birthday": "1999-11-22", "height": 180 }

合并两个字典得到:

{ "name":"owen", "age": 18, "birthday": "1999-11-22", "height": 180 }

方法1

(pthon3已经移除该方法):

dictMerged1 = dict(dict1.items() + dict2.items())
print dictMerged1

方法2:

dictMerged2 = dict( dict1, **dict2 )

方法 2 等同于:

dictMerged2 = dict1.copy()
dictMerged2.update( dict2 )
dictMerged2 = dict( dict1 )
dictMerged2.update( dict2 )

注意:

方法 2 比方法 1 速度快很多, 可以用 IPython 测试效率。

相关文章

网友评论

    本文标题:python合并字典

    本文链接:https://www.haomeiwen.com/subject/zmytxktx.html