脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 详解Python实现字典合并的四种方法

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

2022-11-13 10:39天天开心学编程 Python

这篇文章主要为大家详细介绍了Python的合并字典的四种方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

1、用for循环把一个字典合并到另一个字典

把a字典合并到b字典中,相当于用for循环遍历a字典,然后取出a字典的键值对,放进b字典,这种方法python中进行了简化,封装成b.update(a)实现

?
1
2
3
4
5
6
7
8
9
>>> 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的数据,可以使用这个方法来构造一个新的字典

?
1
2
3
4
5
6
7
8
9
>>> 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)的方法,更新字典

?
1
2
3
4
5
6
7
>>> 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两个字典转换成元组键值对列表

?
1
2
3
4
5
6
7
8
9
10
>>> 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)合并列表并且把合并后的列表转换成字典

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

5、实例,netmiko使用json格式的数据进行自动化操作

(1)json格式的处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#! /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格式的设备信息列表

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[
  {
       "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类型信息示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#! /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字典合并内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/m0_64355682/article/details/123679785

延伸 · 阅读

精彩推荐
  • Pythonpython解决Fedora解压zip时中文乱码的方法

    python解决Fedora解压zip时中文乱码的方法

    这篇文章给大家介绍了如何利用python解决Fedora解压zip时中文乱码的方法,对大家具有一定参考借鉴价值,有需要的朋友们可以参考学习,下面来一起看看吧...

    Python教程网5172020-09-07
  • PythonPytest中conftest.py的用法

    Pytest中conftest.py的用法

    conftest.py文件到底该如何使用呢,下面我们就来详细了解一下conftest.py文件的特点和使用方法吧,感兴趣的小伙伴们可以参考一下...

    RockChe''''s Blog10652021-12-09
  • PythonPython有序字典的两个小“惊喜”

    Python有序字典的两个小“惊喜”

    在Python 3.6 之前,字典是无序的:遍历顺序是随机的。关于有序字典,这里有两件令人意外的事情。...

    Python猫5542020-10-27
  • PythonPython利用heapq实现一个优先级队列的方法

    Python利用heapq实现一个优先级队列的方法

    今天小编就为大家分享一篇Python利用heapq实现一个优先级队列的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    LazyCat_CiCi9812021-05-26
  • PythonAnaconda多环境多版本python配置操作方法

    Anaconda多环境多版本python配置操作方法

    下面小编就为大家带来一篇Anaconda多环境多版本python配置操作方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    conda4762020-12-07
  • Pythonpython 中文编码乱码问题的解决

    python 中文编码乱码问题的解决

    中文编码问题一直是程序员头疼的问题,本文将尽量用通俗的语言带大家彻底的了解字符编码以及Python2和3中的各种编码问题。感兴趣的可以了解一下...

    __Cheny5942022-03-06
  • Python爬虫框架 Feapder 和 Scrapy 的对比分析

    爬虫框架 Feapder 和 Scrapy 的对比分析

    本篇文章在源码层面比对 feapder、scrapy 、scrapy-redis 的设计,阅读本文后,会加深您对 scrapy 以及 feapder 的了解,以及为什么推荐使用 feapder,刚兴趣的朋友可...

    Boris3672022-01-07
  • PythonPyTorch的Debug指南

    PyTorch的Debug指南

    这篇文章主要介绍了PyTorch的Debug的相关资料,帮助大家更好的理解和学习使用PyTorch,感兴趣的朋友可以了解下...

    二十三岁的有德11432021-10-25