Home > Software design >  Using a for loop for a dictionary based on user input
Using a for loop for a dictionary based on user input

Time:11-19

airport_code = input("Please enter your code")

airport_values = {
    'BCN':'Barcelona',
    'DUB':'Dublin',
    'LIS':'Lisbon',
    'LHR':'London Heathrow',
    'CDG':'Paris',
    'PRG':'Prague',
    'RKV':'Reykjavik',
    'FCO':'Rome'
}

if airport_code in airport_values:
    print('The value is:', airport_values[airport_code])
else:
    print("Sorry that item is not in the list ")

Hi, I have written this code to find whether or not the key the user enters matches with one of the values stored in the dictionary airport_values.

When I then looked at the mark scheme it then uses a for loop instead to iterate through the whole dictionary and makes use of a counter to check each value.

Here is the pseudocode which is written in the mark scheme.

https://i.stack.imgur.com/huUdQ.png

What I'm wondering is how I would then apply this to python instead of the way I have done it.

Any help would be much appreciated.

CodePudding user response:

Not that this pseudocode doesn't mean that this is the best solution. In python you can directly check in a dict. Also you there is no int indexing in python.


The kind of iteration in a pythonic way could be that way

for key, value in airport_values.items():
    if key == airport_code:
        print('The value is:', value)
        break
else:
    print("Sorry that item is not in the list ")

The exact pseudocode translation is

i = 0
airports = list(airport_values.items())
while airports[i][0] != airport_code:
    i  = 1
print('The value is:', airports[i][1])

CodePudding user response:

for i in airport_values:
  if airport_code in airport_values:
    print('The value is:', airport_values[airport_code])
    break

for more on python for loops: https://www.w3schools.com/python/python_for_loops.asp

CodePudding user response:

airport_values = {
    'BCN':'Barcelona',
    'DUB':'Dublin',
    'LIS':'Lisbon',
    'LHR':'London Heathrow',
    'CDG':'Paris',
    'PRG':'Prague',
    'RKV':'Reykjavik',
    'FCO':'Rome'
}

airports = list(airport_values.items())
code = input("Please enter code")
i = 0
while airports_list[i][0]!=code:
    i=i 1
print("The airport is: " airports[i][1])
  • Related