I have a .txt file with a list of countries and that countries information separated by commas. My problem is to use that file to create a dictionary, then save that dictionary to a pickled .dat file, and finally import that dictionary so the user can search a countries name and print the information.
I think I created the dictionary and saved it to the dat file correctly, I am having trouble importing the dictionary and searching through it. This is my code for creating and saving the dictionary:
natDict = {}
with open("UN.txt","r") as filestream:
for line in filestream:
currentLine = line.split(",")
newC = Nation(currentLine[0],currentLine[1],float(currentLine[2]),float(currentLine[3])) #creats new Nation object
natDict[currentLine[0]] = newC
with open('nationsDict.dat', 'wb') as handle:
pickle.dump(natDict, handle, protocol=pickle.HIGHEST_PROTOCOL)
Now I have to create a new program that uses the nationsDict.dat file so the user can search for countries. I don't have any experience with pickled dat files and my teacher's lecture slides don't say anything about them. I am guessing I have to import the dat file and then make it a dictionary again so that the user can search it, I just don't know how I am supposed to do it.
//Edit Sorry that the question is a bit unclear, I'll try and give more info. I created an object for each Nation so that the dictionary is like {CountryName: CountryObject}.
class Nation:
def __init__(self, name, cont, pop, area):
self.name = name
self.cont = cont
self.pop = pop
self.area = area
self.popDens = self.calcPopDensity(pop,area)
def calcPopDensity(self,pop,area):
return((pop * 1000000) / area)
def __str__(self):
return (self.name + ":\ncontinent: " + self.cont + "\npopulation: " + str(self.pop) +
" million \narea: " + str(self.area) + "\nPopulation Density : " + str(self.popDens))
The UN.txt file is setup like:
Afghanistan,Asia,31.8,251772
Albania,Europe,3.0,11100
Algeria,Africa,38.3,919595
Andorra,Europe,.085,181
Angola,Africa,19.1,481354
With all nations in the UN in the file.
All I really need to know is how I can use the nationsDict.dat file to search items. I put a dictionary in it, so could I just import it and use it like it is still a dictionary? Or do I have to create a dictionary again with the information in the .data file. Hope this helps.