Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

convert vertical .txt file to dictionary without any library just python basic function

How to convert this .txt file txt file

to this dictionary

here is my code input:


file_harga_rumah = open("harga_rumah.txt", "r")
data_harga_rumah = file_harga_rumah.read()
file_harga_rumah.close()

key_harga_rumah = data_harga_rumah.replace("
",",").split(",")
harga_rumah = []
for baris in key_harga_rumah:
    baris_harga_rumah = baris
    dict_harga_rumah = dict()
    for i in range(len(baris_harga_rumah)):
        harga_rumah[key_harga_rumah[i]] = dict_harga_rumah
    harga_rumah.append(harga_rumah[key_harga_rumah[i]])

output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-115-aeb7087f0ba0> in <module>
      9     dict_harga_rumah = dict()
     10     for i in range(len(baris_harga_rumah)):
---> 11         harga_rumah[key_harga_rumah[i]] = dict_harga_rumah
     12     harga_rumah.append(harga_rumah[key_harga_rumah[i]])

TypeError: list indices must be integers or slices, not str

i can't convert this txt file to dictionary please help:))))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

example:

enter image description here

u can use dictReader:

input_file = csv.DictReader(open(r'c:empfile.txt'))

to display the result:

for row in input_file:
    print(row)

result:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...