2011-11-09 10 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を使用してラベルと一緒にジッパーし、辞書に変換することができます。

# 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であると仮定すると:1つのappend行は、それを打破するために、少し複雑であること

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

。 –

+0

実際、あなたの答えは私が個人的にやることですが、残念ながらリストのcompsはほとんどの人を混乱させます。あなたに+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'が大好きですが、最近はリスト内包表記を使う大きなプッシュがあります。ショーン・チンの答えを参照してください。 –

関連する問題