Problem 3 – Travel destinations Write a program that creates a dictionary called
ID: 3883377 • Letter: P
Question
Problem 3 – Travel destinations Write a program that creates a dictionary called been_to that keeps track of cities that travelers have been to. The dictionary is populated by an input file where each line consists of a traveler’s first name (the key) followed by a list of cities that the person has traveled to (the “value” of the dictionary is a list). For simplicity, we’ll assume that names are unique and cities don’t contain spaces. After reading in the file into a dictionary it should: 1. Output the dictionary 2. Output the name of the person who’s most traveled (been to more cities than anyone else) 3. Output the top destination. Hint: create another dictionary where the key is a city name and the value is the visit count. As you go through cities on each traveler’s list, you update the count for each city. The city with the highest count is the top destination. Sample input file: Jeff DC Seattle Miami Gina Boston Denver Cincinnati Chicago Jose Dallas Denver Chicago Miami PortlandProblem 3 – Travel destinations Write a program that creates a dictionary called been_to that keeps track of cities that travelers have been to. The dictionary is populated by an input file where each line consists of a traveler’s first name (the key) followed by a list of cities that the person has traveled to (the “value” of the dictionary is a list). For simplicity, we’ll assume that names are unique and cities don’t contain spaces. After reading in the file into a dictionary it should: 1. Output the dictionary 2. Output the name of the person who’s most traveled (been to more cities than anyone else) 3. Output the top destination. Hint: create another dictionary where the key is a city name and the value is the visit count. As you go through cities on each traveler’s list, you update the count for each city. The city with the highest count is the top destination. Sample input file: Jeff DC Seattle Miami Gina Boston Denver Cincinnati Chicago Jose Dallas Denver Chicago Miami Portland
Explanation / Answer
#!usr/bin/python
been_to = {}
city = {}
file = open("dict.txt","r")
for line in file:
list = line.split()
key = list.pop(0)
been_to[key] = list
for i in range(len(list)):
city[list[i]] = 1
file.close()
print(been_to)
max = 0
name = ""
for key in been_to.keys():
value = been_to[key]
if len(value) > max:
max = len(value)
name = key
for i in range(len(value)):
city[list[i]] = city[list[i]] + 1
print("The person most travelled:",name)
max = 0
name = ""
for key in city.keys():
value = city[key]
if value > max:
max = value
name = key
print("The top destination is ",name)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.