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

时间:2011-11-09 15:36:20

标签: python file list dictionary split

我在将文件内容转换为词典列表方面遇到了麻烦,你能建议吗?

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

文件夹旁边有多个文件格式相同。最后,我希望收到以下格式的词典列表:

[ {'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'} ]

提前谢谢!

4 个答案:

答案 0 :(得分:8)

首先,您要分割#上的每一行。然后,您可以使用zip将它们与标签一起压缩,然后将其转换为字典。

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

这一个追加线有点复杂,所以要将其分解:

# 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(...)  

答案 1 :(得分:2)

rows = []
for line in input_file:
    r = line.split('#')
    rows.append({'dns':r[0],'ip':r[1],'description':r[2]})

答案 2 :(得分:2)

假设您的文件为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'}]

答案 3 :(得分:2)

>>> map(lambda x : dict(zip(("dns", "ip", "description"), tuple(x.strip().split('#')))), open('input_file'))