Reputation: 70
I am trying to figure out to read a file with multiple line and split the third line as keys and the fourth line as their value
file.txt
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
and desired output like this:
{
"kkk" : "222",
"lll" : "555",
"mmm" : "444",
"nnn" : "666",
"ooo" : "888",
"ppp" : "958",
"qqq" : "555",
"rrr" : "454"
}
Upvotes: 0
Views: 84
Reputation: 17322
you can try:
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)
output:
{'kkk': '222', 'lll': '555', 'mmm': '444', 'nnn': '666', 'ooo': '888', 'ppp': '958', 'qqq': '555', 'rrr': '454'}
Upvotes: 1
Reputation: 401
Maybe there is a simpler solution, but that is what I would do
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)
And that is the output:
{'ooo': '888', 'ppp': '958', 'nnn': '666', 'lll': '555', 'kkk': '222', 'rrr': '454', 'mmm': '444', 'qqq': '555'}
Upvotes: 1