Importing a dicrionary from a file

Wm. King wjk at wjk.mv.com
Wed Jan 5 00:25:54 EST 2000


I am a relative newbie as well - I thought about this
before and had done something along similar lines
but not necessarily the best way:

Created a tab-delimited file (dict.txt) - with no blank lines:
--actually its a table--

a    data something a
b    data something b
c    data something c
d    data something d

then wrote program:

import string                               #import string module
fp = open("dict.txt","r")              #open file
data = fp.readlines()                   #whole file as one variable
new = {}                                     #created empty dictionary
foreach entry in data:                   #entry would be "a    data"
      stuff = string.split(entry,"\t")  #split by tab (now 2 pieces)
      new[stuff[0]] = stuff[1]          #1st part is key 2nd is data

fp.close() #close file

new["a"] would print out data

1. if your keys are numbers just convert the string to a number for
    dictionary key
2. if your file is going to be huge then I would seek an alternative way
3. make sure the separator in your file is a character not used anywhere
    else... ( Field separator in awk lingo me thinks)

I hope I got this right! -- There is probably another way such as just
typing or creating a module with your dictionary in it and using that.
[So I will let the expert Pythonistas help further..... ] (c;{>*

Black Mantis wrote:

> hello
> I am a newbie, and i am working on a program that uses a really big
> dictionary. i was wondering if i could store the dictionary in a
> seperate file, let's say dict.dat. Now, at the beggining of the program
> i want to import that dictionary and get it ready, how would i do this?
> is there a way to read the whole input file into one variable?
>
> thanks for your help
> keagan



Black Mantis wrote:

> hello
> I am a newbie, and i am working on a program that uses a really big
> dictionary. i was wondering if i could store the dictionary in a
> seperate file, let's say dict.dat. Now, at the beggining of the program
> i want to import that dictionary and get it ready, how would i do this?
> is there a way to read the whole input file into one variable?
>
> thanks for your help
> keagan




More information about the Python-list mailing list