In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how to use Python to merge dictionaries. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Merge one dictionary into another using a for loop
Merging a dictionary into b dictionary is equivalent to traversing a dictionary with for loop, then taking out the key-value pair of a dictionary and putting it into b dictionary. This method is simplified in python and encapsulated into 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': 'r1dictionary,' device_type': 'cisco_ios',' username': 'admin',' password': 'cisco'} 2, construct a new dictionary with dict (b, * * a) method
Using the method of * * a, you can quickly open the data of dictionary a, and you can use this method to construct a new dictionary.
> 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, using the method of b.update (a) Update the dictionary > 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. Convert dictionaries into lists after merging And then converted into a dictionary.
Use the method of a.items () to split the dictionary into key-value pair tuples, then force it into a list, merge list (a.items ()) and list (b.items ()), and use dict to convert the merged list into a new dictionary.
(1) use a.items () and b.items () to convert an and b dictionaries into tuple key-value pairs list > 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) merge the list and convert the merged list into a dictionary > dict (list (a.items ()) + list (b.items () {'device_type':' cisco_ios', 'username':' admin', 'password':' cisco', 'name':' r1'} 5, instance Netmiko uses data in json format for automated operations (1) processing in json format #! / usr/bin/env python3# _ * _ coding: utf-8 _ * _ import jsondef 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' generated json list is as follows:\ n {data}') if _ _ name__ = ='_ _ main__': net_name = input ('enter network device name R1 or SW1 form:') device = input ('input device type cisco_ios/huawei:') hostname = input ('enter management IP address:') user = Input ('enter device login user name:') passwd = input ('enter device password:') json_founc = creat_net_device_info json_founc (net_name Device, hostname, user, passwd) (2) list of device information in json format [{"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) example of netmiko reading json type information #! / usr/bin/env python3# _ * _ coding: utf-8 _ * _ import osimport sysimport jsonfrom datetime import datetimefrom netmiko import ConnectHandlerfrom concurrent.futures import ThreadPoolExecutor as Pooldef write_config_file (filename, config_list): with open (filename) 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']) # pass the dictionary in json format into 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% HMI% MMI% S') foldername = this_time old_folder_name = os.path.exists (foldername) if old_folder_name = = True: print ('folder name conflict Program termination\ n') sys.exit () else: os.mkdir (foldername) print (f'is creating directory {foldername}') os.chdir (foldername) print (f 'enter directory {foldername}') net_configs = [] with open (net_info_file_path,'r') as f: devices = json.load (f) # load a list in json format Json.load must pass a separate table 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 ('Please enter the device json_inventory file path:) net_eveng_config_path = input (' Please enter a note The configuration file path of the recording device config path:') main (net_info_file_path Net_eveng_config_path) Thank you for reading! This is the end of the article on "how to use Python to merge dictionaries". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.