2011-11-09 3 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을 사용하여 라벨과 함께 압축 한 다음 사전으로 변환 할 수 있습니다. 하나의 append 줄은 조금 복잡하다

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

일이다. –

+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'을 좋아하지만, 최근에리스트 comprehensions을 사용하는 것이 최근에 강하게 요구됩니다. Shawn Chin의 답변을 참조하십시오. –

관련 문제