python – matching people based on city
students = [ { 'name': 'Sarah', 'city': 'Manchester' }, { 'name': 'Mary', 'city': 'London' } , { 'name': 'Charlotte', 'city': 'Paris' }, { 'name': 'Carl', 'city': 'Paris' } ] my_location = input('Which is your location? ') match_location = [student for student in students if student['city'] == my_location] # Option 1 if len(match_location) > 0: print('The location is:') # Option 2 if any(match_location): print('The location is:')
Here is what the above code is Doing:
1. We create a list of students
2. We ask the user for their location
3. We create a new list of students who match the user’s location
4. We check if the new list is empty
5. If it’s not empty, we print the location