214k views
0 votes
To practice the concept of dictionary as a database Degree of Difficulty: Moderate. Before starting this question, first, download the data file CityData.txt from Canvas. Make sure to put it in the same folder as your a6v1. py python code. Even though this assignment has 5 questions, your solutions to the 5 questions will be submitted in this one file. Write a function called read_citydata () that takes as parameter(s): - a string indicating the name of a city data file This function should return a database (i.e. a dictionary-of-dictionaries) that stores all of the City data in a format that we will describe further below.

1 Answer

3 votes

Final answer:

To create a function that reads a city data file and returns a database, open the file, read its contents, and parse the data to create the dictionary-of-dictionaries database.

Step-by-step explanation:

The question is asking for a function that reads a city data file and returns a database, which is a dictionary-of-dictionaries. To create this function, you will need to open the city data file, read its contents, and then parse the data to create the database. Here is an example of how the function could be implemented:

def read_citydata(filename):
database = {}
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
data = line.split(',')
city = data[0]
population = int(data[1])
area = float(data[2])
density = population / area
database[city] = {'Population': population, 'Area': area, 'Density': density}
return database

In this example, the city data file is assumed to have each line in the format 'city,population,area', where population is an integer and area is a floating-point number. The function reads each line, splits it into the city, population, and area values, calculates the density, and adds the data to the database dictionary with the city as the key. Finally, the function returns the completed database.

User Milkplus
by
7.5k points