l.m
l.m

Reputation: 131

Issue with reading a text file to a dictionary in python

Hey everyone just have an issue with a text file and putting it into a dictionary.

So my code first starts off by gathering data from a website and writes it to a text file. From there I reopen the file and make it into a dictionary to transfer the data from the text to the dictionary. In the while loop, I am getting the error of

 key,value = line.split()
ValueError: too many values to unpack (expected 2)

Which I'm not sure why if I'm using the wrong method to write the text file data to the new place in the program of "countryName"

Then once that compiles I want to be able to ask the user to input a country name and it will give the income capita of that country as shown in the print line.

def main():
    import requests
    webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
    data = requests.get(webFile) #connects to the file and gest a response object
    with open("capital.txt",'wb') as f:
        f.write(data.content) #write the data out to a file – wb used since thecontent from the response object is returned as abinary object.
    f.close()
    infile = open('capital.txt', 'r')
    line = infile.readline()
    countryName = {}
    while line != "":
        key,value = line.split() 
        countryName[key] = value
        line = infile.readline()
    infile.close()
    userInput = input("Enter a country name: ")
    for i in countryName:
        while(userInput != 'stop'):
            print("The per capita income in",countryName[key], "is",countryName[value])
            userInput = input("Enter a country name: ")
main()

Upvotes: 0

Views: 79

Answers (2)

Ville
Ville

Reputation: 129

Split returns list, not dictionary.

a = 'a b c'
list = a.split() #-> ['a','b','c']

Are you trying to do something like:

import requests

webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile).text #connects to the file and gest a response object
print(data)
while(1):
    name = input('Enter a country name: ')
    for a in data.splitlines():
        if name.lower() in a.lower():
            print(a.split()[-1])

Upvotes: 1

Matthew K
Matthew K

Reputation: 86

each line also has a number in the beginning of it, and some country names have spaces in them, causing split to return longer lists. If you use regex to add in semicolons as delimiters, and trim leading and trailing whitespace, the splitting works properly. This code would go inside the first while loop

line = re.sub(r"(\$)", r";\1", line) # add semicolon before $ sign
line = re.sub(r'^([0-9]+)',r'\1;', line) # add semicolon after first group of numbers
num, key, value = re.split(r';', line) # split with semicolons as delimiters
countryName[key.strip()] = value.strip() # assign key and values after stripping whitespace

Upvotes: 2

Related Questions