python:如何从两个文件创建字典


import os
d = {}
with open("time.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)

I havedays.txttime.txt那么如何从两个文件中创建字典呢?

days.txt

Mo Tu We Th Fr

time.txt

19:00 18:00 16:00 20:00 23:00

我的期望输出是

"Mo": 19:00
"Tu": 18:00
"We": 16:00
"Th": 20:00
"Fr": 23:00

我编辑了你的代码,并添加了注释,以便你可以理解:

import os
d = {}
#opening and reading the words from days.txt
days = open("days.txt", 'r').read().split(" ")
#added reading mode to the open function
with open("time.txt", "r") as f:
#Gives an array that reads each word separated by space
f = f.read().split(' ')
#parsing the list by ids is better in my opinion
for i in range(len(f)):
#adding the i element of days to the dict and element i of f as the value
d[days[i]] = f[i]
print(d)

见下。读取2个文件-压缩数据并生成字典

with open('time.txt') as f1:
t = f1.readline().split()
with open('days.txt') as f2:
d = f2.readline().split()
data = dict(p for p in zip(d,t))
print(data)

输出
{'Mo': '19:00', 'Tu': '18:00', 'We': '16:00', 'Th': '20:00', 'Fr': '23:00'}

相关内容

  • 没有找到相关文章

最新更新