简体   繁体   中英

read text file and put into dictionary

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"
}

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'}

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM