python - 将文件转换为字典

标签 python string file dictionary

我如何获取文件的内容并将其更改为字典? 内容将包括以下形式的菜单项:

1 Chocolate ice cream
2 Green tea
 8 Shrimp roll

我希望键是数字,值是食物。

到目前为止,我得到了:

d = {}
for line in menu.read().strip().split():
      d[line[0]] = d[line[1:]]
return d

但结果是有偏差的...

最佳答案

逐行遍历文件对象,然后拆分行:

with open('inputfilename.txt') as menu:
    d = {}
    for line in menu:
        key, value = line.split(None, 1)
        d[key] = value.strip()
    return d

.split(None, 1) 调用应用默认拆分算法(在任意宽度的空白处拆分),但将其限制为仅一个 拆分以仅返回2 项。优点是 以空格开头 的行(例如您帖子中的 ' 8 Shrimp roll' 行)也得到了正确处理,因为在拆分之前删除了前导空格。

这会产生:

{'2': 'Green tea', '1': 'Chocolate ice cream', '8': 'Shrimp roll'}

关于python - 将文件转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17813915/

相关文章:

c - C 预处理器能够逐字符处理字符串吗?

C - 附加到字符串 - 可能的内存错误

c++ 无法改进文件读取?

Java - 尝试写入文件 2 次或更多次时出现 BufferOverflowException

python - Keras - 是否可以在 Tensorboard 中查看模型的权重和偏差

python - Heroku Django 应用程序错误 : 'module' has no attribute 'TemporaryDirectory'

python - 如何在python中将列表列表转换为数据框

c# - 如何根据某些条件从 Dictionary<string, List<string>> 中选择/删除元素

linux - 在 Jenkins 多配置作业中复制文件

javascript - python Selenium : Click on a specific Dropdown containing Java