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

Categories

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:))))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...