天天看點

Python中字典(dict)合并的幾種方法Python中字典(dict)合并的幾種方法

Python中字典(dict)合并的幾種方法

文章目錄

  • Python中字典(dict)合并的幾種方法
    • 一、字典的update()方法
    • 二、字典的dict(d1, **d2)和(**d1,**d2)方法
      • 1.dict(d1, **d2)
      • 2.dict(**d1,**d2)
    • 三、字典的正常處理方法

輸出結果均為:

{'name': 'coulson', 'age': '25', 'ins': 'hkx303', 'company': 'redhat'}
           

一、字典的update()方法

common = {'name': 'coulson', 'age': '25'}
social = {'ins': 'hkx303', 'company': 'redhat'}
info = {}
info.update(common)
info.update(social)
print(info)

           

二、字典的dict(d1, **d2)和(**d1,**d2)方法

1.dict(d1, **d2)

common = {'name': 'coulson', 'age': '25'}
social = {'ins': 'hkx303', 'company': 'redhat'}
info = dict(common, **social)
print(info)

           

2.dict(**d1,**d2)

common = {'name': 'coulson', 'age': '25'}
social = {'ins': 'hkx303', 'company': 'redhat'}
info = dict(**common, **social)
print(info)

           

三、字典的正常處理方法

common = {'name': 'coulson', 'age': '25'}
social = {'ins': 'hkx303', 'company': 'redhat'}
info = dict(**common, **social)
for key, value in common.items():
    info[key] = value
for key, value in social.items():
    info[key] = value
print(info)