Home > Net >  Trying to print a specific key and value from dictionary based on user input
Trying to print a specific key and value from dictionary based on user input

Time:09-25

I have a program that requires me to to access a dictionary with zip codes and city names called

countyzips = {'90210': 'Beverly Hills', '90001' : 'Los Angeles', etc.}

If the zipcode is in the dictionary I want to have the program print "zip code = 90210 , city = Beverly Hills" for example. And if the zip code is not in the dictionary print "zip code xxxxx is not in Los Angeles County. Right now I can't seem to get the program to work.

Here is my code so far

 zip = input('enter zip code:')
        for x,y in countyzips.items():
            if x in countyzips:
                print (f'zipcode = {x} , city = {y}')
            else:
                print (f'zip code = {x} not in Los Angeles county')

CodePudding user response:

You can use simple in operator to check if key is in the dictionary:

countyzips = {"90210": "Beverly Hills", "90001": "Los Angeles"}

zip_ = input("enter zip code:")

if zip_ in countyzips:
    print(f"zip code = {zip_}, city = {countyzips[zip_]}")
else:
    print(f"zip code = {zip_} is not in Los Angeles County")

Prints (for example):

enter zip code:90210
zip code = 90210, city = Beverly Hills

Note: don't use names like zip, list etc. They shadow Python builtins.

CodePudding user response:

Something like the below. The idea is to use county_zips.get that will return None in case there is no city for the given zip code.

county_zips = {'90210': 'Beverly Hills', '90001': 'Los Angeles'}

zip_ = input('Type the zip please:')
city = county_zips.get(zip_)
if city is not None:
    print(f' The zip code {zip_} belongs to the city {city}')
else:
    print(f'The zip code {zip_} does not belong to a city in L.A county')

CodePudding user response:

Provided you have no indentation errors, your code doesn't work because you loop over every key/value pair in the dictionary as x,y, and check if x is actually a valid zip-code. You don't actually check anything about the zip-code that was entered (zip).

Note: you shouldn't use names of built-in functions in Python like zip as variable names. Pick something that hasn't been used yet, like zipcode.

A working version:

countyzips = {'90210': 'Beverly Hills', '90001' : 'Los Angeles'}

zipcode = input('enter zip code:')
if zipcode in countyzips:
    print (f'zipcode = {zipcode} , city = {countyzips[zipcode]}')
else:
    print (f'zip code = {zipcode} not in Los Angeles county')

CodePudding user response:

dict raises a KeyError if a key is not in the dictionary. Use that to your advantage.

countyzips = {'90210': 'Beverly Hills', '90001' : 'Los Angeles'}
zipcode = input('enter zip code:')
try:
    print(f'zipcode = {zipcode} , city = {countyzips[zipcode]}')
except KeyError:
    print(f'zip code = {zipcode} not in Los Angeles county')

~

  • Related