欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python實(shí)現(xiàn)字典合并的四種方法

 更新時(shí)間:2022年03月24日 17:01:29   作者:天天開心學(xué)編程  
這篇文章主要為大家詳細(xì)介紹了Python的合并字典的四種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

1、用for循環(huán)把一個(gè)字典合并到另一個(gè)字典

把a(bǔ)字典合并到b字典中,相當(dāng)于用for循環(huán)遍歷a字典,然后取出a字典的鍵值對(duì),放進(jìn)b字典,這種方法python中進(jìn)行了簡化,封裝成b.update(a)實(shí)現(xiàn)

>>> 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)方法構(gòu)造一個(gè)新字典

使用**a的方法,可以快速的打開字典a的數(shù)據(jù),可以使用這個(gè)方法來構(gòu)造一個(gè)新的字典

>>> 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、把字典轉(zhuǎn)換成列表合并后,再轉(zhuǎn)換成字典

利用a.items()的方法把字典拆分成鍵值對(duì)元組,然后強(qiáng)制轉(zhuǎn)換成列表,合并list(a.items())和list(b.items()),并使用dict把合并后的列表轉(zhuǎn)換成一個(gè)新字典

(1)利用a.items()、b.items()把a(bǔ)、b兩個(gè)字典轉(zhuǎn)換成元組鍵值對(duì)列表

>>> 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)合并列表并且把合并后的列表轉(zhuǎn)換成字典

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

5、實(shí)例,netmiko使用json格式的數(shù)據(jù)進(jìn)行自動(dòng)化操作

(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('輸入網(wǎng)絡(luò)設(shè)備名稱R1或者SW1的形式:')
   device = input('輸入設(shè)備類型cisco_ios/huawei: ')
   hostname = input('輸入管理IP地址: ')
   user = input('輸入設(shè)備登錄用戶名: ')
   passwd = input('輸入設(shè)備密碼: ')
   json_founc = creat_net_device_info
   json_founc(net_name, device, hostname, user, passwd)

(2)json格式的設(shè)備信息列表

[
  {
       "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'正在創(chuàng)建目錄 {foldername}')
       os.chdir(foldername)
       print(f'進(jìn)入目錄 {foldername}')
?
   net_configs = []
?
   with open(net_info_file_path, 'r') as f:
       devices = json.load(f) #載入一個(gè)json格式的列表,json.load必須傳入一個(gè)別表
?
   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('請(qǐng)輸入設(shè)備json_inventory文件路徑: ')
   net_eveng_config_path = input('請(qǐng)輸入記錄設(shè)備config路徑的配置文件路徑: ')
   main(net_info_file_path, net_eveng_config_path)

到此這篇關(guān)于詳解Python實(shí)現(xiàn)字典合并的四種方法的文章就介紹到這了,更多相關(guān)Python字典合并內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中對(duì)字典的幾個(gè)處理方法分享

    Python中對(duì)字典的幾個(gè)處理方法分享

    這篇文章主要介紹了Python中對(duì)字典的幾個(gè)處理方法分享,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下
    2022-08-08
  • 利用python如何處理nc數(shù)據(jù)詳解

    利用python如何處理nc數(shù)據(jù)詳解

    目前很多數(shù)據(jù)以nc格式存儲(chǔ),下面這篇文章主要給大家介紹了關(guān)于利用python如何處理nc數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值。需要的朋友們下面來一起看看吧
    2018-05-05
  • Python完全新手教程

    Python完全新手教程

    Python完全新手教程...
    2007-02-02
  • python密碼學(xué)一次性密碼的實(shí)現(xiàn)

    python密碼學(xué)一次性密碼的實(shí)現(xiàn)

    這篇文章主要為大家介紹了python密碼學(xué)一次性密碼的實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • pytorch自定義初始化權(quán)重的方法

    pytorch自定義初始化權(quán)重的方法

    今天小編就為大家分享一篇pytorch自定義初始化權(quán)重的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python讀取excel中的圖片完美解決方法

    Python讀取excel中的圖片完美解決方法

    excel中的圖片非常常見,但是通過python讀取excel中的圖片沒有很好的解決辦法。今天小編給大家分享一種比較聰明的方法,感興趣的朋友跟隨腳本之家小編看看吧
    2018-07-07
  • python 裝飾器功能以及函數(shù)參數(shù)使用介紹

    python 裝飾器功能以及函數(shù)參數(shù)使用介紹

    之前學(xué)習(xí)編程語言大多也就是學(xué)的很淺很淺,基本上也是很少涉及到裝飾器這些的類似的內(nèi)容??偸怯X得是一樣很神奇的東西,舍不得學(xué)(嘿嘿)。今天看了一下書籍。發(fā)現(xiàn)道理還是很簡單的
    2012-01-01
  • python中協(xié)程實(shí)現(xiàn)TCP連接的實(shí)例分析

    python中協(xié)程實(shí)現(xiàn)TCP連接的實(shí)例分析

    在本篇文章中我們給大家分享了python中協(xié)程實(shí)現(xiàn)TCP連接的代碼示例內(nèi)容,有需要的朋友們可以跟著學(xué)習(xí)下。
    2018-10-10
  • Python的None和C++的NULL用法解讀

    Python的None和C++的NULL用法解讀

    這篇文章主要介紹了Python的None和C++的NULL用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • python 循環(huán)數(shù)據(jù)賦值實(shí)例

    python 循環(huán)數(shù)據(jù)賦值實(shí)例

    今天小編就為大家分享一篇python 循環(huán)數(shù)據(jù)賦值實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12

最新評(píng)論