Reputation: 35
I'm fairly new to Python. At the moment, I have a text file called 'action_table2.txt' where the contents look like this:
1: Goals
2: Dreams
3: Environment
4: Outside
5: Inside
6: Reality
7: Allies
8: Enemies
9: Evil
10: Good
...
I want to turn each line into a key:value entry in a dictionary called action_table2, but at this rate, the only way I know how to do it is to copy and paste the table into python, then manually type quotation marks outside of each 'value' and then manually add a comma after each one. This is extremely tedious (especially since I'm doing this for multiple tables).
I've tried printing out each line with formatting so I could then copy and paste it already formatted the way I want, but I couldn't see how to add quotation marks, just commas or extra text.
I've also tried this code:
action_table2 = {}
with open('action_table2.txt') as f:
for line in f:
key, value = line.strip().split(':')
action_table2[key] = (value)
but when I try to retrieve the key, I get a key error. (This is what it looks like when I try to retrieve it:)
import random
print(action_table2[random.randint(1,100)])
Upvotes: 1
Views: 88
Reputation: 4487
The problem is that the type returned by rand.randint
is different from the type of your key. You can do two things:
import random
action_table2 = {}
with open('action_table2.txt') as f:
for line in f:
key, value = line.strip().split(': ')
action_table2[int(key)] = value
print(action_table2[random.randint(1, len(action_table2))])
random.randint
in string:import random
action_table2 = {}
with open('action_table2.txt') as f:
for line in f:
key, value = line.strip().split(': ')
action_table2[key] = value
print(action_table2[str(random.randint(1, len(action_table2)))])
In both cases I replaced the split(":")
with split(": ")
to avoid having a space as the first character of the value
If you prefer you can also solve your problem using dict comprehension:
action_table2 = {s.split(':')[0]: s.strip().split(': ')[1] for s in f}
Upvotes: 1
Reputation: 36608
You need to convert the keys from strings to integers.
action_table2 = {}
with open('action_table2.txt') as f:
for line in f:
key, value = line.strip().split(':')
action_table2[int(key)] = (value)
Upvotes: 2