2020年12月31日星期四

How to create a Python dictionary from data imported from a text file?

I have the following text in a file named 'my_text.txt':

David: 2  Barbara: 97.2  David: nothing  William:    Lynn: 725  Nancy   : 87       David:       54  Lewis: 18.30  Sue:   3193.74  James: 41.73    David: 974.1  

I would like to be able to read this file and create a dictionary. Here is my code:

def make_dictionary(file_name):        d = {}        with open(file_name, 'r') as file:          for line in file:              (key, val) = (line.split(':')[0], line.split(':')[1])        return print(d)    make_dictionary('my_text.txt')  

I'm getting an index error:

IndexError:  list index out of range  

Does anyone see where the mistake is?

Thanks!

https://stackoverflow.com/questions/65526746/how-to-create-a-python-dictionary-from-data-imported-from-a-text-file January 01, 2021 at 09:37AM

没有评论:

发表评论