0

In python, how would i select a single character from a txt document that contains the following:

A#

M*

N%

(on seperate lines)...and then update a dictionary with the letter as the key and the symbol as the value.

The closest i have got is:

ftwo = open ("clues.txt", "r")
for lines in ftwo.readlines():
    for char in lines:

I'm pretty new to coding so cant work it out!

2 Answers2

0

Supposing that each line contains extactly two characters (first the key, then the value):

with open('clues.txt', 'r') as f:
    myDict = {a[0]: a[1] for a in f}

If you have empty lines in your input file, you can filter these out:

with open('clues.txt', 'r') as f:
    myDict = {a[0]: a[1] for a in f if a.strip()}
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • I think that you need to create the empty dictionary and then add the individual key elements. I think that your code resets the dictionary to each individual row so that you are left with only the final input of a as the single entry in the dictionary. – sabbahillel Mar 11 '14 at 19:54
0

First, you'll want to read each line one at a time:

my_dict = {}
with open ("clues.txt", "r") as ftwo:
    for line in ftwo:
        # Then, you'll want to put your elements in a dict
        my_dict[line[0]] = line[1]
njzk2
  • 38,969
  • 7
  • 69
  • 107