Austin H. Austin H. - 1 month ago 6
Python Question

How do I make one item in a list == to an item in another list?

For example, I am trying to be able to have the user input a province like "alberta" and then have it display "AB" to the user. Or the other way around. I can only use lists. (The instructor mention something about "parallel lists"?) I am just a beginner, but this is what I tried...

def lists (province, abrev):
userInput = input("Enter Province or Abreviation: ")
province = ["alberta", "nova scotia", "british columbia"]
abrev = ["AB", "NS", "BC"]
for ab in range(len(province)):
if province["alberta"] == abrev["AB"]:
print("AB")
if userInput == province:
print(len(province))
def main():

lists()

main()

Answer

You can use zip() to join two lists together.

province = ["alberta", "nova scotia", "british columbia"]
abrev = ["AB", "NS", "BC"]

userInput = input("Enter Province or Abreviation: ")

for prov,ab in zip(province,abrev):
    if userInput == prov:
        print(ab)
    elif userInput == ab:
        print(prov)

Alternatively you can use dictionaries. With this method you have a key and a value

province_dict = {'NS': 'nova scotia', 'BC': 'british columbia', 'AB': 'alberta'}

If you want to lookup what state has the abbreviation 'AB' then you would do

print(province_dict['AB'])

Since you are dealing with user input you should use

province_dict.get(userInput,'Unknown')

This will return 'Unknown' if the item is not found in the dictionary rather than raising a KeyError.