CoDyDaTallGuy
CoDyDaTallGuy

Reputation: 65

prompt a user to enter a key in a dictionary to output its value

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

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 77007

There are a few things you can improve in your code:

  1. You are not initializing the dict with values, do it.

  2. You can use PEP compliant variable names like country_name instead of countryName

  3. 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

Related Questions