Reputation: 65
I've been trying to figure out ways to get the users input of a specify key in order to output its corresponding value. Thing is I'm not too sure if I set up my dictionary correctly. I have to define a dictionary with an attached text file and in that text file each line has a country name, a space, and income which looks similar to something like this - "Qatar $129,700".
My thing is, how do I get it to where I can type in the countries name and have it output it's correct income value?
Current code:
import string
import re
import fileinput
infile = open("C:\\Users\\mrbal\\Desktop\\Homework
Assignments\\percapita.txt", "r")
dict1 = {}
for line in infile:
x = line.split(" ")
countryName = x[0]
income = x[1]
print(countryName, income)
print("##############################")
#country = input("Please enter the desired country: ")
First, did I set up the dictionary correctly?
Second, in this current setup, when I run the program it outputs the contents of my file which is good, but I still need the user to input a country from the dictionary and then have it output its value. How would I go about doing that?
Upvotes: 1
Views: 910
Reputation: 77007
There are a few things you can improve in your code:
You are not initializing the dict with values, do it.
You can use PEP compliant variable names like country_name
instead of countryName
You open the file but don't close it. Use with
to avoid this.
So, the code becomes:
import string
import re
import fileinput
with open("C:\\Users\\mrbal\\Desktop\\Homework Assignments\\percapita.txt", "r") as infile:
incomes = {}
for line in infile:
x = line.split(" ")
country_name, income = x[0], x[1]
print(country_name, income)
incomes[country_name] = income
print("##############################")
country = input("Please enter the desired country: ")
print(incomes.get(country, "No information found for country %s" % country))
If you would like to give list of country to the user, just add an additional print statement:
print("Options for country are: %s" % incomes.keys())
Upvotes: 1