2011-11-09 83 views
6

我在将文件内容转换为词典列表时遇到麻烦,您能否提供建议?python:读取文件并将其分割成词典列表

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

提前致谢!

回答

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(...) 
+0

+1了详细的解释。 –

+0

其实,你的答案就是我会亲自做的,但不幸的是,列表比赛混淆了大多数人。 +1给你。 –

2
rows = [] 
for line in input_file: 
    r = line.split('#') 
    rows.append({'dns':r[0],'ip':r[1],'description':r[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'}] 
2
>>> map(lambda x : dict(zip(("dns", "ip", "description"), tuple(x.strip().split('#')))), open('input_file')) 
+0

我喜欢'map'和下一个人一样多,但最近有一个大推动使用列表解析,而不是。看到Shawn Chin的回答。 –

相关问题