简体   繁体   English

python:读取和拆分文件到词典列表

[英]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! 先感谢您!

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. 然后,您可以使用zip将它们与标签一起压缩,然后将其转换为字典。

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(...)  
rows = []
for line in input_file:
    r = line.split('#')
    rows.append({'dns':r[0],'ip':r[1],'description':r[2]})

Assuming your file is infile.txt 假设你的文件是infile.txt

>>> 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'}]
>>> map(lambda x : dict(zip(("dns", "ip", "description"), tuple(x.strip().split('#')))), open('input_file'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM