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.4254 Voting
Ümran
Usta · 5 yıl öğretmeniUzman doğrulaması
Cevap
Here is the Python code that reads the file, parses each line, and stores the city data in a dictionary:<br />```python<br /># Open the file in read mode<br />with open('cities.txt', 'r') as file:<br /> # Initialize an empty dictionary to store the city data<br /> cities = {}<br /><br /> # Read each line from the file<br /> for line in file:<br /> # Split the line by semicolons to get the city name, country, and population<br /> city_name, country, population = line.strip().split(';')<br /><br /> # Add the city data to the dictionary<br /> cities[city_name] = [country, int(population)]<br /><br /># Print the contents of the dictionary<br />for city, data in cities.items():<br /> print(f"{city} ({data[1]}): {data[0]}")<br />```<br />This code will output the following:<br />```css<br />Rome (2760000): Italy<br />Tokyo (37000000): Japan<br />Paris (2148000): France<br />Rio de Janeiro (6211000): Brazil<br />```
Derecelendirmek için tıklayın: