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

print (d)

I have days.txt and time.txt so how to create dictionary from the two file.

days.txt

Mo Tu We Th Fr

time.txt

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

My expected output is

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

2 Answers

0
votes

I edited your code and put the comments so you can understand:

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)
0
votes

See below. Read the 2 files - zip the data and generate a 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)

output

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