iszack freeman
iszack freeman

Reputation: 1

nesting multiple dictionaries, possibly lists?

I am trying to build a python program to take a users input of the year of the car, and after that the model (no need for the make it will only contain fords). And with the year and model, the program will reference to the correct year and model and get the corresponding capacity information of the vehicle (engine oil, coolant, brake fluid etc.).

My question comes in with, how do I go about storing that information?
I was thinking to make a car_list dict and to the key years nest the first year 1998 inside that nest a list of the cars in that year, and in each car nest a dictionary of the specs.

car_list = {'years' : {1998 : [{'accord': {'oil' : '4.0 qts', 'coolant': '2 gals'} 'civic': {'oil': '4.5 qts', 'coolant': '3 gals'}]}

Will this work? Am I going about this wrong?

Upvotes: 0

Views: 165

Answers (3)

michaelmao
michaelmao

Reputation: 21

Simple program that may solve your problem (in python3):

model=input("model:")
year=input("year:")
query={model1:{year1:specs1,year2:specs2 ... }, model2:{ ... } ... }
print(query[model][year])

The specs could be either list or dictionary. It depends on how you want to use the data. The program would prompt for user input and then print you the specs of the intended year and model as either a list or a dictionary. The output should be manipulated to fit your needs.

Upvotes: 2

manyfoo
manyfoo

Reputation: 81

You can store all the information in a nested dictionary, I think that's the best way. The dictionary can look like this:

car_list = {"1998":{"ka":["4.0 qts", "2 gals"], 
                    "fiesta":["3.0 qts", "2.3 gals"]},
            "2001":{"kuga":["3.3 qts", "3 gals"], 
                    "mondeo":["4.0 qts", "3.5 gals"]}}

If you ask the user via input() for the year and car, you can print the information all by once if you use a for-loop:

input_year = input("Year?\n> ")
input_car = input("Car?\n> ")

for info in car_list[input_year][input_car]:
    print(info)

or give them the information one by one:

input_year = input("Year?\n> ")
input_car = input("Car?\n> ")
i = car_list[input_year][input_car]

print("Oil: {}\nCoolant: {}".format(i[0], i[1]))

Upvotes: 0

Ishaq Khan
Ishaq Khan

Reputation: 173

Using dictionary is a good idea here. But your code doesn't look right. Use this format:

car_list = {'1998' : {'accord': {'oil' : '4.0 qts', 'coolant': '2 gals'}, 'civic': {'oil': '4.5 qts', 'coolant': '3 gals'}}}

print(car_list['1998']['civic']['oil'])

Upvotes: 0

Related Questions