import os
d = {}
with open("time.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)
我有days.txt和time.txt那么如何從這兩個檔案創建字典。
天.txt
Mo Tu We Th Fr
時間.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
uj5u.com熱心網友回復:
我編輯了您的代碼并添加了注釋,以便您可以理解:
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)
uj5u.com熱心網友回復:
見下文。讀取 2 個檔案 - 壓縮資料并生成一個 dict
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'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312969.html
標籤:字典
