2011-11-09 19 views
6

Dosya içeriğinin sözlük listesine dönüştürülmesinde sıkıntı yaşıyorum, tavsiye edebilir misiniz?python: sözlükleri listesine okuyabilir ve bölebilirsiniz

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 

tarafında birden fazla dosya aynı biçime sahip klasör vardır. Sonunda aşağıdaki biçimde bir sözlükler listesi almak istiyorum:

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

Önceden teşekkürler!

cevap

8

İlk olarak, her satırı #'a bölmek istiyorsunuz. Daha sonra, etiketlerle birlikte sıkıştırmak ve ardından bir sözlüğe dönüştürmek için zip'u kullanabilirsiniz. bir ekleme çizgisi biraz karmaşık

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

Yani, bu yüzden yıkmak için:

# 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 olduğunu. –

+0

Aslında, cevabınız kişisel olarak ne yapardım, ama maalesef listelerin çoğu insanı karıştırır. +1 size de. –

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

Dosyanızı varsayarsak ayrıntılı bir açıklama için 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

Bir sonraki adama 'haritayı' seviyorum, ancak son zamanlarda liste anlamalarını kullanmak için büyük bir itici güç var. Shawn Chin'in cevabı. –

İlgili konular