Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: read and split files in to list of dictionaries

I'm having troubles with converting file content into list of dictionaries, could you 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

There are multiple files in side the folder with the same format. At the end I would like to receive 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!

like image 269
m1k3y3 Avatar asked Nov 09 '11 15:11

m1k3y3


2 Answers

First, you want to split each line on #. Then, you can use zip to zip them together with the labels, then convert it to a dictionary.

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

That one append line is a bit complex, so to break it down:

# 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(...)  
like image 64
Donald Miner Avatar answered Sep 17 '22 22:09

Donald Miner


rows = []
for line in input_file:
    r = line.split('#')
    rows.append({'dns':r[0],'ip':r[1],'description':r[2]})
like image 34
Tyler Eaves Avatar answered Sep 19 '22 22:09

Tyler Eaves