Parsing text file in Python into a dictionary

喜夏-厌秋 提交于 2021-01-28 05:43:48

问题


I have a csv file. I want to create dictionary from this data.I should not pandas. Data looks like this:

I do this. But size of the numbers is not same. How can I create a dictionary?

filename=" data.dat"
file=open(filename, encoding="latin-1").read().split(' , ')
dictt={}

for row in file:
    dictt[row[0]] = {‘values’, row[1]}

I have a file as above. First, I need to create a dict. After that, I will print the daily number of unique measurements in desending order according to date.

Final Expected result:


回答1:


Hi
That will do what you want

with open("./test.txt") as myFile:
    formattedData = dict()
    for line in myFile:
        try:
            date , numbers = line.split(' , ')
            numbers = numbers.replace("\n","") 
            numbers = numbers.split(',')
            formattedData[date] = len(list(set(numbers)))
        except:
            date = line
            formattedData[date] = 0
print(formattedData)




回答2:


Firstly, do not call your variables 'list' as that is a python keyword and it will cause confusion. I can't reproduce this because I don't have the file, but I think changing the line in the for loop to this should work.

newvariablename[row[0]] = row[1]


来源:https://stackoverflow.com/questions/65274300/parsing-text-file-in-python-into-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!