2024-06-06 20:18:01 -04:00
|
|
|
import json
|
2024-06-06 22:19:00 -04:00
|
|
|
from typing import Any, Dict, List
|
|
|
|
|
|
|
|
|
|
|
|
def get_cars() -> Any: # Defining the function get_cars()
|
|
|
|
with open('cars.json', 'rt') as f: # Opens the cars.json file
|
|
|
|
return json.load(f) # Serializes the JSON data into a Python object
|
|
|
|
|
|
|
|
def sort(data: Dict[str, str]) -> Dict[str, List[str]]: # Defining the function sort()
|
|
|
|
dictionary: Dict[str, List[str]] = {} # Creating an empty dictionary to store the sorted data
|
|
|
|
for car, manufacturer in data.items(): # Iterating through the input data
|
|
|
|
if manufacturer not in dictionary: # If the manufacturer does not already exist as a key in the new dictionary,
|
|
|
|
dictionary[manufacturer] = [car] # create a new key with the manufacturer as the key and the car as the value, in a list
|
|
|
|
else: # If the manufacturer does already exist as a key in the new dictionary,
|
|
|
|
dictionary[manufacturer].append(car) # append the car to the list of cars for that manufacturer
|
|
|
|
return dictionary # Return the dictionary object
|
|
|
|
|
|
|
|
def save(data: Dict[str, Any]) -> None:
|
|
|
|
with open('sorted_cars.json', 'w') as f: # Opening the file sorted_cars.json for the purpose of writing to it
|
|
|
|
json.dump(data, f, indent=2) # Dumps the JSON-serialized python object into the sorted_cars.json file, with an indentation of 2
|
2024-06-06 20:18:01 -04:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2024-06-06 22:19:00 -04:00
|
|
|
cars = get_cars()
|
|
|
|
sorted_cars = sort(cars)
|
|
|
|
save(sorted_cars)
|
|
|
|
print("Successfully sorted cars by manufacturer!")
|