How can I convert strings in a .txt file to dictionary elements?
Let's say I have a file "stuff.txt" which contains the following lines on separate lines: d: 5 d: 2 s: 7
I want to read each of these lines from a file and convert them to dictionary elements, with letters being keys and value numbers. So I would like to get y = {"q": 5, "r": 2, "s": 7}
I tried the following but it just prints an empty dictionary "{}"
y = {}
infile = open("stuff.txt", "r")
z = infile.read()
for line in z:
key, value = line.strip().split(':')
y[key].append(value)
print(y)
infile.close()
source to share
try this:
d = {}
with open('text.txt') as f:
for line in f:
key, value = line.strip().split(':')
d[key] = int(value)
You add to d[key]
as if it were a list. What you want is to just set it up like above.
Also, using with
to open a file is good practice, as it automatically closes the file after executing the code in "with a block".
source to share
There are some possible improvements. The first is using a context manager to handle the files - this with open(...)
is - in case of an exception, this will handle all the necessary tasks for you.
Secondly, you have a small mistake in the dictionary assignment: values are assigned using the = operator, for example dict [key] = value.
y = {}
with open("stuff.txt", "r") as infile:
for line in infile:
key, value = line.strip().split(':')
y[key] = (value)
print(y)
source to share