如何将.txt文件写入python字典

问题描述

Name 1
car/machines
taxi
motorcycle

Name 2
address
phone number
age
education,school

Name 3
datetime
favorite

我想创建一个字典来将名称保存为键,并将名称下的详细信息保存为值。 输出示例:

{'Name 1': ['car/machines','taxi','motorcycle'],'Name 2': ['address','phone number','age','education,school'] 'Name 3': ['datetime','favorite']}

解决方法

下面的代码虽然有点笨拙,但可以工作,也许您可​​以找到一个更好的解决方案,但是这个解决方案相当快。

#Reading the text file
text = open('text.txt','r')
#Turning it into a list of lines
lines = text.readlines()
#Defining the last name variable
#For later use
last_name = str()
#Defining the dict
lines_dict = dict()
#The +1 is there because i need to append the list to the key
#At the last iteration
for x in range(len(lines)+1):
    #The try is here because it will overflow
    try:
        #Stripping the line of the newline character
        lines[x] = lines[x].strip()
        #Check if the 'Name' string is in the line in question
        if 'Name' in lines[x]:
            #If there is any last name
            if 'Name' in last_name:
                #Filter the dictionary of empty spaces
                temp_list = list(filter(None,temp_list))
                #Appends the value to the key in the dict
                lines_dict[last_name] = temp_list
            #Getting the last name
            last_name = lines[x]
            #Resseting the temp list
            temp_list = list()
        #If the string is not 'Name'
        else:
            #Append the string to the temp list
            temp_list.append(lines[x])
    #If it overflows
    except Exception as e:
        #Do the last appending
        lines_dict[last_name] = temp_list
,
d = {}
with open('data.txt') as f:
    for s in f.read().split('\n\n'):
        lines = s.split('\n')
        d[lines[0]] = lines[1:]
print(d)

这假设您的数据文件中没有换行符。