2011-11-09 33 views
6

Tôi gặp khó khăn khi chuyển đổi nội dung tệp thành danh sách từ điển, bạn có thể tư vấn không?python: đọc và chia nhỏ các tệp vào danh sách từ điển

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 

Có nhiều tệp ở bên thư mục có cùng định dạng. Cuối cùng, tôi muốn nhận danh sách từ điển có định dạng sau:

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

Cảm ơn bạn trước!

Trả lời

8

Trước tiên, bạn muốn chia từng dòng trên #. Sau đó, bạn có thể sử dụng zip để nén chúng cùng với các nhãn, sau đó chuyển đổi nó thành từ điển.

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

Đó là một dòng append là một chút phức tạp, vì vậy để phá vỡ nó xuống:

# 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 cho lời giải thích chi tiết. –

+0

Trên thực tế, câu trả lời của bạn là những gì tôi sẽ làm cá nhân, nhưng tiếc là danh sách comps gây nhầm lẫn cho hầu hết mọi người. 1 cho bạn là tốt. –

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

Giả sử tập tin của bạn là 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

Tôi yêu 'map' nhiều như anh chàng tiếp theo, nhưng gần đây có một sự thúc đẩy lớn để sử dụng tính năng đọc danh sách, thay vào đó. Xem câu trả lời của Shawn Chin. –

Các vấn đề liên quan