python - 将文件转换为字典?
问题描述
我有一个 txt 文件列出名称和年龄:
John,20
Mary,14
Kevin,60
Mary,15
John,40
并尝试编写以下函数来返回字典:
def read(filename):
results = {}
with open(os.path.join(os.path.dirname(__file__), 'data.txt')) as file:
for line in file:
location,value = line.split(',', 1)
results[location] = value
print(results)
我正在尝试格式化为:
{'John': [20, 40], 'Mary': [14, 15], 'Kevin': [60]}
但目前得到:
{'John': '20', 'Mary': '15\n', 'Kevin': '60\n'}
谁能帮我理解我做错了什么?
解决方案
您需要测试该键是否在字典中,如果没有则添加一个空列表。将当前值添加到键的列表中:
def read(filename):
results = {}
with open(os.path.join(os.path.dirname(__file__), 'data.txt')) as file:
for line in file:
if line.strip(): # guard against empty lines
location,value = line.strip().split(',', 1) # get rid of \n
if location not in results:
results[location] = []
results[location].append( int(value) ) # as number
print(results)
如果需要,您可以查找dict.setdefault(key,defaultvalue)
并collections.defaultdict
获得更多性能 - 在这里:collections.defaultdict 如何工作?
推荐阅读
- python - python错误中的随机密码生成器
- javascript - 使用 NodeJS 发送自动电子邮件
- javascript - 正则表达式捕获两种不同的格式
- python - 模型错误,TypeError: on_delete 必须是可调用的
- sql - 甲骨文 SQL。如何在“THEN”输出一个字母后跟 4 个数字的语句时创建一个案例
- powershell - 使用 RDP 登录时应用 GPO
- reactjs - FieldArray fields.push({ no, id }) - 没有属性可以显示,但 id 属性不能
- swift - SwiftUI 中 Picker 的增量范围
- gdb - 无法通过修改 EIP 寄存器执行系统功能
- javascript - JavaScript 的 element.appendChild() 方法表现怪异