简体   繁体   中英

How to import a text file into a dictionary

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.

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM