首頁 > 軟體

詳解Python實現字典合併的四種方法

2022-03-24 19:00:13

1、用for迴圈把一個字典合併到另一個字典

把a字典合併到b字典中,相當於用for迴圈遍歷a字典,然後取出a字典的鍵值對,放進b字典,這種方法python中進行了簡化,封裝成b.update(a)實現

>>> a = {'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b = {'name': 'r1'}
>>> for k, v in a.items():
...     b[k] =  v
... 
>>> a
{'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b
{'name': 'r1', 'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}

2、用dict(b, **a)方法構造一個新字典

使用**a的方法,可以快速的開啟字典a的資料,可以使用這個方法來構造一個新的字典

>>> a = {'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b = {'name': 'r1'}
>>> c = dict(b, **a)
>>> c
{'name': 'r1', 'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> a
{'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b
{'name': 'r1'}

3、用b.update(a)的方法,更新字典

>>> a = {'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b = {'name': 'r1'}
>>> b.update(a)
>>> a
{'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b
{'name': 'r1', 'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}

4、把字典轉換成列表合併後,再轉換成字典

利用a.items()的方法把字典拆分成鍵值對元組,然後強制轉換成列表,合併list(a.items())和list(b.items()),並使用dict把合併後的列表轉換成一個新字典

(1)利用a.items()、b.items()把a、b兩個字典轉換成元組鍵值對列表

>>> a = {'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco'}
>>> b = {'name': 'r1'}
>>> a.items()
dict_items([('device_type', 'cisco_ios'), ('username', 'admin'), ('password', 'cisco')])
>>> b.items()
dict_items([('name', 'r1')])
>>> list(a.items())
[('device_type', 'cisco_ios'), ('username', 'admin'), ('password', 'cisco')]
>>> list(b.items())
[('name', 'r1')]

(2)合併列表並且把合併後的列表轉換成字典

>>> dict(list(a.items()) + list(b.items()))
{'device_type': 'cisco_ios', 'username': 'admin', 'password': 'cisco', 'name': 'r1'}

5、範例,netmiko使用json格式的資料進行自動化操作

(1)json格式的處理

#! /usr/bin/env python3
# _*_ coding: utf-8 _*_
import json
​
def creat_net_device_info(net_name, device, hostname, user, passwd):
   dict_device_info = {
                       'device_type': device,
                       'ip': hostname, 
                       'username': user, 
                       'password': passwd
                      }
   dict_connection = {'connect': dict_device_info}
   dict_net_name = {'name': net_name}
   data = dict(dict_net_name, **dict_connection)
   data = json.dumps(data)
   return print(f'生成的json列表如下:n{data}')
​
​
if __name__ == '__main__':
   net_name = input('輸入網路裝置名稱R1或者SW1的形式:')
   device = input('輸入裝置型別cisco_ios/huawei: ')
   hostname = input('輸入管理IP地址: ')
   user = input('輸入裝置登入使用者名稱: ')
   passwd = input('輸入裝置密碼: ')
   json_founc = creat_net_device_info
   json_founc(net_name, device, hostname, user, passwd)

(2)json格式的裝置資訊列表

[
  {
       "name": "R1", 
       "connect":{
           "device_type": "cisco_ios",
           "ip": "192.168.47.10",
           "username": "admin",
           "password": "cisco"
      }
  },
  {
       "name": "R2", 
       "connect":{
           "device_type": "cisco_ios",
           "ip": "192.168.47.20",
           "username": "admin",
           "password": "cisco"
      }
  },
  {
       "name": "R3", 
       "connect":{
           "device_type": "cisco_ios",
           "ip": "192.168.47.30",
           "username": "admin",
           "password": "cisco"
      }        
  },
  {
       "name": "R4", 
       "connect":{
           "device_type": "cisco_ios",
           "ip": "192.168.47.40",
           "username": "admin",
           "password": "cisco"
      }    
  },
  {
       "name": "R5", 
       "connect":{
           "device_type": "cisco_ios",
           "ip": "192.168.47.50",
           "username": "admin",
           "password": "cisco"
      }
  }
]

(3)netmiko讀取json型別資訊範例

#! /usr/bin/env python3
# _*_ coding: utf-8 _*_
​
import os
import sys
import json
from datetime import datetime
from netmiko import ConnectHandler
from concurrent.futures import ThreadPoolExecutor as Pool
​
def write_config_file(filename, config_list):
   with open(filename, 'w+') as f:
       for config in config_list:
           f.write(config)
​
def auto_config(net_dev_info, config_file):
   ssh_client = ConnectHandler(**net_dev_info['connect']) #把json格式的字典傳入
   hostname = net_dev_info['name']
   hostips = net_dev_info['connect']
   hostip = hostips['ip']
   print('login ' + hostname + ' success !')
   output = ssh_client.send_config_from_file(config_file)
   file_name = f'{hostname} + {hostip}.txt'
   print(output)
   write_config_file(file_name, output)
   
def main(net_info_file_path, net_eveng_config_path):
   this_time = datetime.now()
   this_time = this_time.strftime('%F %H-%M-%S')
   foldername = this_time
   old_folder_name = os.path.exists(foldername)
   if old_folder_name == True:
       print('資料夾名字衝突,程式終止n')
       sys.exit()
   else:
       os.mkdir(foldername)
       print(f'正在建立目錄 {foldername}')
       os.chdir(foldername)
       print(f'進入目錄 {foldername}')
​
   net_configs = []
​
   with open(net_info_file_path, 'r') as f:
       devices = json.load(f) #載入一個json格式的列表,json.load必須傳入一個別表
​
   with open(net_eveng_config_path, 'r') as config_path_list:
       for config_path in config_path_list:
           config_path = config_path.strip()
           net_configs.append(config_path)
​
   with Pool(max_workers=6) as t:
       for device, net_config in zip(devices, net_configs):
           task = t.submit(auto_config, device, net_config)
       print(task.result())    
​
​
if __name__ == '__main__':
   #net_info_file_path = '~/net_dev_info.json'
   #net_eveng_config_path = '~/eve_config_path.txt'
   net_info_file_path = input('請輸入裝置json_inventory檔案路徑: ')
   net_eveng_config_path = input('請輸入記錄裝置config路徑的組態檔路徑: ')
   main(net_info_file_path, net_eveng_config_path)

到此這篇關於詳解Python實現字典合併的四種方法的文章就介紹到這了,更多相關Python字典合併內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com