我正在尝试读取多行的文件,并将第三行拆分为键,将第四行拆分为值
file.txt
v, ok := setting.(map[string]map[string][]map[string]string)
和所需的输出是这样的:
Ext: aaa bbb ccc ddd eee fff ggg hhh
tcp: 000 111 222 333 444 555 666 777
Ext: kkk lll mmm nnn ooo ppp qqq rrr
tcp: 222 555 444 666 888 958 555 454
答案 0 :(得分:1)
您可以尝试:
with open('test.txt', 'r') as fp:
lines = [e.strip() for e in fp.readlines()]
my_dict = {l3 :l4 for l3, l4 in zip(lines[2].split()[1:], lines[3].split()[1:])}
print(my_dict)
输出:
{'kkk': '222', 'lll': '555', 'mmm': '444', 'nnn': '666', 'ooo': '888', 'ppp': '958', 'qqq': '555', 'rrr': '454'}
答案 1 :(得分:1)
也许有一个更简单的解决方案,但这就是我要做的
file = open("path_to_your_file.txt", "r")
file.readline()
file.readline()
keys = file.readline().split()[1:]
values = file.readline().split()[1:]
d = dict(zip(keys, values))
file.close()
print(d)
这就是输出:
{'ooo': '888', 'ppp': '958', 'nnn': '666', 'lll': '555', 'kkk': '222', 'rrr': '454', 'mmm': '444', 'qqq': '555'}