iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >详解Python实现字典合并的四种方法
  • 151
分享到

详解Python实现字典合并的四种方法

2024-04-02 19:04:59 151人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录1、用for循环把一个字典合并到另一个字典2、用dict(b, **a)方法构造一个新字典3、用b.update(a)的方法,更新字典4、把字典转换成列表合并后,再转换

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字典合并内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解Python实现字典合并的四种方法

本文链接: https://www.lsjlt.com/news/143813.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作