Anasayfa
/
Teknoloji
/
Part 1 (40pts): A Text File Named Cities.but Contains Information About Various Cities. Each Line of the File Contains a City Name, Its

Soru

Part 1 (40pts): A text file named cities.but contains information about various cities. Each line of the file contains a city name, its country, and its population, separated by semicolons (;). Sample file content: Rome; Italy;2760000 Tokyo; Japan; 37000000 Paris;Fr ance :2148000 __ Write Python statements that read the file, parse each line, and store the city data in a dictionary where each key is a city name and value is a list of its country and its population, then print the contents of this dictionary as seen in the sample run below (in the format: city name (its population): its country). Created dictionary of cities will look like: I'Rome ['Italy", 2760000], "Tokyo': ['Japan , 370000001, Part 1: Cities: Rome (2760000): Italy Tokyo (37000000): Japan 148000): F rance __ Rio de Jane izo (6211000): B razil

Çözüm

4.4 (254 Oylar)
Ümran
Uzman doğrulaması
Usta · 5 yıl öğretmeni

Cevap

Here is the Python code that reads the file, parses each line, and stores the city data in a dictionary:```python# Open the file in read modewith open('cities.txt', 'r') as file: # Initialize an empty dictionary to store the city data cities = {} # Read each line from the file for line in file: # Split the line by semicolons to get the city name, country, and population city_name, country, population = line.strip().split(';') # Add the city data to the dictionary cities[city_name] = [country, int(population)]# Print the contents of the dictionaryfor city, data in cities.items(): print(f"{city} ({data[1]}): {data[0]}")```This code will output the following:```cssRome (2760000): ItalyTokyo (37000000): JapanParis (2148000): FranceRio de Janeiro (6211000): Brazil```