Reputation: 19
I am having trouble importing a text file into a dictionary in Python.
I have a Python file which currently looks like this:
Dictionary = {}
with open("File.txt", "r") as f:
for line in f:
(key, val) = line.split()
Dictionary[int(key)] = val
within the text file (File) is text like this:
j ^
m +
d !
I need to import the text from this file so that the dictionary reads this in and I can then use it later in my program to change letters to symbols and symbols to letters.
Upvotes: 0
Views: 3996
Reputation: 384
I think I know what program you're writing. It may just be a guess but since I am doing one very similar for my GCSE.... Anyway the way I did this was
Dictionary = {}
with open('clues.txt') as f:
for l in f:
Dictionary[l[0]] = l[1]
Upvotes: -1
Reputation: 12737
I did this:
Dictionary = {}
with open("File.txt", "r") as f:
for line in f:
(key, val) = line.split()
Dictionary[key] = val
(So ... don't try to turn the key letters into integers) and got this:
In [8]: Dictionary
Out[8]: {'d': '!', 'j': '^', 'm': '+'}
Seems to work fine.
You were using [int(key)]
but your keys are all letters and Python's int()
built-in expects a number. int()
will take any number, even if that number is stored as a string and convert it to an integer. You don't need integers for your dictionary.
Upvotes: 3