【问题标题】:Reading information from a txt file and storing it in a dictionary从一个txt文件中读取信息并存入字典
【发布时间】:2022-11-19 19:58:30
【问题描述】:

我需要从 txt 文件中获取信息并将其存储到字典中

字典中只存储了一行信息,如何存储所有行?

text = '''
admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No
admin, Assign initial tasks, Use taskManager.py to assign each team member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No

'''


tasks = {}

with open('tasks.txt', 'r', encoding='utf-8') as file:
    
    for line in file:
        temp = line.split(", ")
        user = temp[0]
        title = temp[1]
        description = temp[2]
        due_date = temp[3]
        date_assigned = temp[4]
        status = temp[5]
        
        tasks[user] = {'title': title, 'description': description, 'due date': due_date, 'date assigned': date_assigned, 'status': status}

print(tasks)

【问题讨论】:

  • 请不要提供数据的外部链接或屏幕截图。将合理大小的数据样本作为文本发布。
  • 好的,我马上编辑
  • tasks 是您想要的字典。所以它只接受唯一的条目,重复的条目被覆盖。 txt 文件中的两行都有用户admin,因此只有一个条目。

标签: python dictionary


【解决方案1】:

你的结果字典中有相同的键admin,第一个被第二个替换,所以修改你的文本文件以提供不同的名称

【讨论】:

  • 在这种情况下,管理员需要为同一用户执行不同的任务。我不能用字典来做这个吗?
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多