1
1
Fork 0
PythonLearning/cars/main.py
Seaswimmer bfceebd171
Some checks failed
Lint Code / Ruff (push) Successful in 9s
Lint Code / MyPy (push) Failing after 13s
Lint Code / Pylint (push) Failing after 13s
finished Cars
Co-authored-by: raymondlopez279@gmail.com <raymondlopez279@gmail.com>
2024-06-06 22:19:00 -04:00

26 lines
1.7 KiB
Python

import json
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
if __name__ == '__main__':
cars = get_cars()
sorted_cars = sort(cars)
save(sorted_cars)
print("Successfully sorted cars by manufacturer!")