Python: reading and splitting files into a dictionary list

I am having problems converting the contents of a file into a list of dictionaries, could you please advise?

File content: host1.example.com#192.168.0.1#web server host2.example.com#192.168.0.5#dns server host3.example.com#192.168.0.7#web server host4.example.com#192.168.0.9#application server host5.example.com#192.168.0.10#database server 

A folder with the same format has several files. In the end, I would like to get a list of dictionaries with the following format:

 [ {'dns': 'host1.example.com', 'ip': '192.168.0.1', 'description': 'web_server'}, {'dns': 'host2.example.com', 'ip': '192.168.0.5', 'description': 'dns server'}, {'dns': 'host3.example.com', 'ip': '192.168.0.7', 'description': 'web server'}, {'dns': 'host4.example.com', 'ip': '192.168.0.9', 'description': 'application server'}, {'dns': 'host5.example.com', 'ip': '192.168.0.10', 'description': 'database server'} ] 

Thank you in advance!

+6
source share
4 answers

First you want to split each line into # . Then you can use zip to pin them along with tags, and then convert to a dictionary.

 out = [] labels = ['dns', 'ip', 'description'] for line in data: out.append(dict(zip(labels, line.split('#')))) 

This add line is a bit complicated, so break it:

 # makes the list ['host2.example.com', '192.168.0.7', 'web server'] line.split('#') # takes the labels list and matches them up: # [('dns', 'host2.example.com'), # ('ip', '192.168.0.7'), # ('description', 'web server')] zip(labels, line.split('#')) # takes each tuple and makes the first item the key, # and the second item the value dict(...) 
+8
source
 rows = [] for line in input_file: r = line.split('#') rows.append({'dns':r[0],'ip':r[1],'description':r[2]}) 
+2
source

Assuming your infile.txt file

 >>> entries = (line.strip().split("#") for line in open("infile.txt", "r")) >>> output = [dict(zip(("dns", "ip", "description"), e)) for e in entries] >>> print output [{'ip': '192.168.0.1', 'description': 'web server', 'dns': 'host1.example.com'}, {'ip': '192.168.0.5', 'description': 'dns server', 'dns': 'host2.example.com'}, {'ip': '192.168.0.7', 'description': 'web server', 'dns': 'host3.example.com'}, {'ip': '192.168.0.9', 'description': 'application server', 'dns': 'host4.example.com'}, {'ip': '192.168.0.10', 'description': 'database server', 'dns': 'host5.example.com'}] 
+2
source
 >>> map(lambda x : dict(zip(("dns", "ip", "description"), tuple(x.strip().split('#')))), open('input_file')) 
+2
source

Source: https://habr.com/ru/post/901126/


All Articles