我试图将单个列表分成单独的两个子字符串,然后在字典中将它们作为键,值附加。
我尝试的方法是将列表拆分为较小的子字符串,然后将索引0处的项目作为键附加,将索引1作为字典中的值附加。
E.g
输入test.txt
Writing Fast Tests Against Enterprise Rails 60min
Overdoing it in Python 45min
预期输出
{'Writing Fast Tests Against Enterprise Rails': 60,
'Overdoing it in Python': 45}
到目前为止,我的方法是将列表切割成较小的子字符串。
d = {}
lines = [line.strip() for line in open('test.txt')]
for line in lines:
print(line.split(maxsplit=1))
上面的代码产生以下输出
['Writing', 'Fast Tests Against Enterprise Rails 60min']
['Overdoing', 'it in Python 45min']
如何对列表进行切片,以便将名称和时间切换为子字符串,然后将其附加到字典中。
由于
答案 0 :(得分:3)
谢谢@Ashwini,我得到了正确的输出。这很简单。
d = {}
lines = [line.strip() for line in open('test.txt')]
for line in lines:
title, minutes = line.rsplit(maxsplit=1)
d[title] = int(minutes[:-3])
print(d)