m1k*_*3y3 6 python dictionary split file list
我将文件内容转换为字典列表时遇到了麻烦,你能建议吗?
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
Run Code Online (Sandbox Code Playgroud)
文件夹旁边有多个文件具有相同的格式.最后,我希望收到以下格式的词典列表:
[ {'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'} ]
Run Code Online (Sandbox Code Playgroud)
先感谢您!
首先,您要分开每一行#
.然后,您可以使用zip
它们与标签一起压缩它们,然后将其转换为字典.
out = []
labels = ['dns', 'ip', 'description']
for line in data:
out.append(dict(zip(labels, line.split('#'))))
Run Code Online (Sandbox Code Playgroud)
那个追加线有点复杂,所以要分解它:
# 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(...)
Run Code Online (Sandbox Code Playgroud)