nesting multiple dictionaries, possibly lists? - python

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?

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.

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'])

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]))

Related

Usage of a dictionary, Right or wrong?

I'm creating a car sales program and need to use a dictionary, I have a basic understanding of them. Would it be efficient to hold the car name as a string for the key, then store the relevant cars selling price in the values through a list? for example,
Audi1Price = 1000
Audi2Price = 1500
Cars = ["Audi": [Audi1Price, Audi2Price]]
Can this work? Is there a better usage for the dictionary?
Maybe there's a better way to work with the selling price as I'd like to print it out too, I'm unsure. Thanks
Yes, that could work.
There is a problem in your example code, though: you used [] instead of {} for the dictionary.
You need to do this:
Audi1Price = 1000
Audi2Price = 1500
Cars = {
"Audi": [Audi1Price,Audi2Price]
}

Calling methods and iterating over list

I'm trying to ask for ingredients in a recipe via the input function. I want to store that ingredient in a dictionary, separated by quantity and ingredient. For example, an input of '3 eggs', should yield {'3': 'eggs'}.
The way i do this is with the separate() and convert_to_dict() methods.
I want to ask continuously for the ingredients by means of the input, hence the while True loop.
Basically, i do this via the following code:
ingredients_list = []
def separate(list):
for i in list:
return re.findall(r'[A-Za-z]+|\d+', i)
def convert_to_dict(list):
i = iter(list)
dct = dict(zip(i, i))
return dct
while True:
ingredient = input("Please input your ingredient: ")
ingredients_list.append(ingredient)
print(convert_to_dict(separate(ingredients_list)))
This works fine, but the only problem with it is that when i input another ingredient, the separate() and convert_to_dict() methods only seem to work for the first ingredient in the ingredient list. For example, i firstly input '3 eggs', and then '100 gr of flour', yet it only returns {'3': 'eggs'}. I'm sure there is something i'm missing, but can't figure out where it goes wrong.
I think you've got the idea of your key-value pairs the wrong way around!
Keys are unique. Updating a dictionary with an existing key will just override your value. So if you have 3 eggs, and 3 cups of sugar, how do you envision your data structure capturing this information?
Rather try doing -
{'eggs': 3} # etc.
That should sort out a lot of problems...
But that's all besides the point of your actual bug. You've got a return in your for-loop in the separate function...This causes the function to return the first value encountered in the loop, and that's it. Once a function's reached a return in exist the function and returns to the outer scope.

Python - Getting Items From List Using Day Name

I am trying to make a program that gets the date, works out what lessons i have.
import datetime
def getdate():
now = datetime.datetime.now()
print(now.strftime("%A"))
day=getdate()
##LESSON LIST###
################
Lessons = [
Monday=['English','Geography','German','P.E.','Science-C']
Tuesday=['Art','Science-B','Maths','ICT','French']
Wednesday=['History','English','Drama','Science-B','Maths']
Thursday=['P.E.','D&T','HTT','Geography','R.E.']
Friday=['German','D&T','Maths','English','Music']
]
################
#END LESSON LIST
Today = Lessons[day]
print("1) Book Check")
print("2) Timetable List")
x = input()
if x = 1:
#List lessons for this day one by one with a book input eg.
print("book for lesson1")
l1 = bool(input("True/False"))
print("book for lesson2")
l2 = bool(input("True/False"))
#but it should say the lesson name, and save the state of book boolean
elif x = 2:
#list lessons for this day
print(Today) # just an example.
Currently, I get a syntax error that I cannot fix, I can't find where I have gone wrong. I would like to use a dictionary to complete my code but I am unsure how to.
First you have a major error in how you are trying to form a dict. It should be this:
Lessons = {
'Monday':['English','Geography','German','P.E.','Science-C'],
'Tuesday':['Art','Science-B','Maths','ICT','French'],
'Wednesday':['History','English','Drama','Science-B','Maths'],
'Thursday':['P.E.','D&T','HTT','Geography','R.E.'],
'Friday':['German','D&T','Maths','English','Music']
}
This is a dictionary called Lessons that has Strings as keys (the days of the weeks) and Lists as values (The lists of lessons). To access a list of lessons you would do it like so:
Lessons['Monday']
Note that this returns a list, if you want it formatted differently, then you can do something like this:
", ".join(Lessons['Monday'])
This will give you a comma-separated list of lessons.
I am unsure what exactly you are trying to do with books, but if you want to be more specific I will update my answer. However, I can say that if you will be running this program each day, then you will need to store information about the books in a file to maintain their state, otherwise it will be lost when the program ends.
Also, variables should be lower-cased (lessons instead of Lessons), but I kept it how you had it to be consistent.

Convert User Input into a List name

Here is what I have so far:
TotalLists=int(input("How many Lists are you making?"))
TotalListsBackup=TotalLists
Lists=[]
while TotalLists>0:
ListName=input("What would you like to call List Number "+str(TotalLists))
Lists.append(ListName)
TotalLists=TotalLists-1
TotalLists=TotalListsBackup-1
while TotalLists>=0:
Lists[TotalLists] #I would like to create actual lists out of the list names at this step but I dont know how...
TotalLists=TotalLists-1
TotalLists=TotalListsBackup-1
print("Here are your Lists: ")
while TotalLists>=0:
print(Lists[TotalLists])
TotalLists=TotalLists-1
I want to be able to:
create a List out of the List Names
The code to be able to make as many lists as the user wants to without a cap
For example, I want to input: Grocery,
The code will create a list Called Grocery
Solutions I have thought of:
Arrays? (I have never used them, I am very new to Python Programming and I dont know too much)
Lists of Lists? (Not sure how to do that. Looked it up, but didn't get a straight answer)
Using Variables, Creating a list with a name like:
List1[]
and have varible called:
List1Name=input("What would you like to call list 1?")
I do not know how to create an infinite number of lists using this way though.
If you have any questions please ask, for I know I am not good at explaining.
It's interesting that you have tagged the question "dictionary" but didn't mention that in your post. Did somebody tell you to use a dictionary? That's exactly what you should be doing, like this (assume TotalLists is already defined):
d = {}
for _ in range(TotalLists): # The same loop you have now
ListName = input("whatever...")
d[ListName] = []
At the end of this you have a dictionary d containing keys that are the user-entered names, and values that are empty lists. The number of dictionary entries is TotalLists. I'm ignoring the possibility that the user will enter the same name twice.
You're solving an XY problem. There's no need to ask for the number of lists in advance. I would recommend using a dictionary:
>>> lists = {}
>>> while 1:
... newlist = input("Name of new list (leave blank to stop)? ")
... if newlist:
... lists[newlist] = []
... while 1:
... newitem = input("Next item? ")
... if newitem:
... lists[newlist].append(newitem)
... else:
... break
... else:
... break
...
Name of new list (leave blank to stop)? groceries
Next item? apples
Next item? bananas
Next item?
Name of new list (leave blank to stop)? books
Next item? the bible
Next item? harry potter
Next item?
Name of new list (leave blank to stop)?
>>> lists
{'groceries': ['apples', 'bananas'], 'books': ['the bible', 'harry potter']}

Dictionary/Database key value retrieval

As stated in a previous (but different) question, I'm trying to figure out a 'simple' dictionary/database with Python, which will retrieve a name from a list of ten, with the requested information. i.e. input could be 'John phone', where the output is 'John's phone number is 0401' (which I have down pat); but I could also input 'John Birthday' or 'John hobbies' and the output would correspond.
As I'm a complete noob, I'm not even sure where to start. Several hours of googling and poring over lecture notes have yielded nothing so far.
I've got the feeling it's got something to do with the multiple argument % function but our lecturer really wasn't clear about how to take it further.
So far, what I have is:
#!/usr/bin/python
friends = {'John': {'phone' : '0401',
'birthday' : '31 July',
'address' : 'UK',
'interests' : ['a', 'b', 'c']},
'Harry': {'phone' : '0402',
'birthday' : '2 August',
'address' : 'Hungary',
'interests' : ['d', 'e', 'f']}}
name = raw_input ('Please enter search criteria: ')
if name in friends:
print "%s's phone number is: %s" % (name, friends[name]['phone'])
else:
print 'no data'
I'd also like to use the 'while' function so the prog doesn't close as soon as that information is given, but not sure if this would be appropriate.
Any pointers would be great, even if it's a 'try this' kind of hint, or a link to a relevant website.
Since this is homework, I'll limit my answer to some hints:
tok = name.split() would split name into a list of words, so 'John address' would become ['John', 'address'].
You can access the individual words as tok[0] and tok[1], and use them to index into friends to get the relevant person and then the relevant field.
I see no problem with wrapping the input/search logic into a while loop so that the user can perform multiple queries. The only thing to figure out is how you're going to exit that loop.
Based on your sample code, 'John phone' wouldn't work since it would actually be looking up 'John phone' as the name (and 'phone' is hardcoded). For illustration, try code like this:
response = raw_input('Please enter search criteria: ').split()
try:
print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
except KeyError:
print 'no data'
the split() takes each argument separately which can then be referenced with [0] and [1] (and so forth). You were already on the right track with % substitution, but this approach will give it more usability and readability.
The key is that you shouldn't need to check if the name matches (or the criteria matches). Assume it'll be there--and in the event of an exceptional case (that the matches aren't found), it can return 'no data' as expected.
Please enter search criteria: John phone
John's phone is 0401
Please enter search criteria: Harry birthday
Harry's birthday is 2 August
Listen to aix for the first part of your question. For the second part, I'd suggest coming up with an exit value (perhaps 'exit') that the user could type to leave the program, then have your while loop keep going while input is not that value.

Categories

Resources