Skip to content Skip to sidebar Skip to footer

Value Search From Dictionary Via User Input

I have written the following code for getting an output of the various districts located in the given city and their respective postal codes. I want my code to be able to receive i

Solution 1:

The program does only execute the two print statements print(d_district) and print(d_code), where you actually just dump the contents of the zipcode dictionary. Your first print statement is never reached, as the condition never gets fulfilled. You have to compare to the value and not the key of the dictionary.

For the reversed case, you can check if the string entered by the user is numeric, and if this is the case, you just search for the zipcode in the same manner.

mydistrict=input('Enter your district: ')

if mydistrict.strip().isnumeric():
    for city in zipcode:
        for district in zipcode[city]:
            if zipcode[city][district] == int(mydistrict.strip()):
                print(city,zipcode[city][district])
else:
    for city in zipcode:
        if mydistrict in zipcode[city]:
            print(city,zipcode[city][mydistrict])

Solution 2:

Googled the results. Dont know python. Might be working just for this example: Try:

import pandas as pd
import re

 def get_dis_cit():
    zpdf =pd.DataFrame(zipcode)#zipdataframe
    inpt =  input('Enter your zip code or your district: ')

    if inpt.isnumeric(): 
        zpdf = zpdf==int(inpt)
        district = list(zpdf.columns[zpdf.any()]) + list(zpdf.index[zpdf.T.any()])
        return dict(zip(["city","District"], district))
    else:
       district = re.search('\\b'+inpt+"[^']*",str(zipcode),re.I).group()
       city = list(zpdf.loc[district].dropna().index)
       return dict(zip(city, [district] * len(city)))

Results

get_dis_cit()

Enter your zip code or your district: 100
Out[71]: {'city': 'Trap City', 'District': 'C District'}

get_dis_cit()

Enter your zip code or your district: 200
Out[72]: {'city': 'Zap City', 'District': 'R District'}

get_dis_cit()

Enter your zip code or your district: r dist
Out[73]: {'city': 'Zap City', 'District': 'R District'}

get_dis_cit()

Enter your zip code or your district: Y DISTRICT
Out[74]: {'city': 'Los City', 'District': 'Y District'}

get_dis_cit()

Enter your zip code or your district: D dist
Out[75]: {'Trap City': 'D District', 'Zap City': 'D District'}

Data:

zipcode = {
    "Trap City": {
        "C District": 100,
        "D District": 103,
        "E District": 104,
        "S District": 105
    },
    "Zap City": {
        "R District": 200,
        "D District": 201
    },
    "Los City": {
        "X District": 207,
        "Y District": 208
    }
}

Post a Comment for "Value Search From Dictionary Via User Input"