python 合併字典的方法

【方法一】藉助dict(d1.items() + d2.items())的方法

d1 = {'usr':'root','pwd':'1234'}
d2 = {'ip':'192.168.1.11','port':'8088'}
d3 = dict(d1.items() + d2.items())
print d3
結果:
{'ip':'192.168.1.11','pwd':'1234','usr':'root','port':'8088'}

備註:
1. d1.items()獲取字典的鍵值對的列表
2. d1.items() + d2.items()拼成一個新的列表
3. dict(d1.items()+d2.items())將合併成的列表轉變成新的字典

【方法二】藉助字典的update()方法

d1 = {'usr':'root','pwd':'1234'}
d2 = {'ip':'192.168.1.11','port':'8088'}
d3 = {}
d3.update(d1)
d3.update(d2)
print d3
結果:
{'ip':'192.168.1.11','pwd':'1234','usr':'root','port':'8088'}

或者
d3 = d1.copy()
d3.update(d2)
print d3
結果:
{'ip':'192.168.1.11','pwd':'1234','usr':'root','port':'8088'}

【方法三】藉助字典的dict(d1, **d2)方法.—-【推薦】

d1 = {'usr':'root','pwd':'1234'}
d2 = {'ip':'192.168.1.11','port':'8088'}
d3 = dict(d1,**d2)
print d3
結果:
{'ip':'192.168.1.11','pwd':'1234','usr':'root','port':'8088'}

【方法四】藉助字典的常規處理方法

d1 = {'usr':'root','pwd':'1234'}
d2 = {'ip':'192.168.1.11','port':'8088'}
d3 = {}
for k,v in d1.items():
    d3[k]=v

for k,v in d2.items():
    d3[k]=v
print d3
結果:
{'ip':'192.168.1.11','pwd':'1234','usr':'root','port':'8088'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章