# Sets up a dictionary. Heh. Like you'd find in a library.
# It took me an EMBARASSINGLY long time to remember that dictionaries exist, will help!
books = {
"Fiction": 0,
"Non-Fiction": 0,
"Science": 0,
"History": 0,
}
# Remembering dictionaries existed has GIVEN ME UNLIMITED POWER! Having maximum stock set in a dictionary helps get rid of "magic numbers"
MAXIMUM_STOCK = {
"Fiction": 30,
"Non-Fiction": 20,
"Science": 15,
"History": 25,
}```
Part two of my assignment is here, and before I move onto the "first" step, I wanna see if I can combine my two dictionaries here into a single dictionary. Is this possible? I'm aware I will have to change a lot of code down the line, but for my assignment I need to change code anyway, so how can I combine these? Cheers!
#π Combining Multiple Dictionaries into a single Dictionary
49 messages Β· Page 1 of 1 (latest)
@bleak oyster
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
I feel like something like:
books = {
"Fiction": 30, 0,
"Non-Fiction": 20, 0,
"Science": 15, 0,
"History": 25, 0,
}```
Might be how to do it, but I'm not 100% sure.
Except that gives me an invalid syntax error.
Well actually it's giving me a : expected after dictionary key
Which yeah gives me a syntax error if I try to run.
But if I replace the final commas with colons, it gives me an invalid syntax when it gets to "Non-Fiction".
do u know lists/tuples
so use those for dict values
I'm not 100% sure how to do so in this case.
books = {
Fiction["1"] = [30, 0]
Non-Fiction["2"] = [20, 0]
Science["3"] = [15, 0]
History["4"] = [25, 0]
}```
Is this correct?
this is closer to correct
to make a list u just do [1,2,3,4]
tuples its ()
dict its {} and : btw key,value pairs
just {} would be set, like {1,2,3,4}
I'm a bit confused.
Does the code I posted seem like I'm on the right track?
I need to store the maximum value that the genre can have, as well as be able to add or withdraw books from it.
In that case, what am I doing incorrectly? To me the code I posted seems more like "Combining a dictionary and a list" but I'm not 100% sure.
this is very close to correct
when you make a list, you put [] around the elements of the list
So then like this? @grand seal?
kind of
the keys in the first one are correct, the values in the second one are correct
books = {
"Fiction": [30, 0]
"Non-Fiction": [20, 0]
"Science": [15, 0]
"History": [25, 0]
}```
This, then?
As in, a comma after the []?
yep
"Fiction": [30, 0],
yes
Very good.
Downside of doing this all is I will have to change a lot of my code π
But I think this is more useful in the long run, since I need to both store this in an external file and be able to add new genres.
Am I able to say, modify the numbers in the list using the same code? Or is the fact it's now in a list going to mean I have to change everything?
else:
# selected_genre becomes a key with which we can access our dictionary
# subtracts 1 from the genres so that user input lines up with dictionary.
selected_genre = genres[selection - 1]
if books[selected_genre] < MAXIMUM_STOCK[selected_genre]:
books[selected_genre] += 1
# Our f-string lets us print the genre and how many books are in it.
print(f"You have successfully returned a {selected_genre} book.")
print(f"You now have {books[selected_genre]} {selected_genre} book(s)")
break
else:
print(f"Error 5 ({selection}): Returning exceeds inventory maximum.")```
This for example, is my code which returns a book to the chosen genre.
Obviously, MAXIMUM_STOCK will soon cease to exist, since it's being merged in with the books dictionary.
I'm gonna finish studying for the day, but thanks for the help.
yes, you can still edit the contents of the dict but with a little more work.
books[selected_genre] becomes books[selected_genre][1] (element at index 1 in the list).
MAXIMUM_STOCK[selected_genre] becomes books[selected_genre][0]
Excellent, thank you so much.
!e
d1 = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
d2 = {'A': 6, 'B': 7, 'C': 8, 'D': 9}
d3 = {k: (v, d2[k]) for k, v in d1.items()}
print(d3)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
{'A': (1, 6), 'B': (2, 7), 'C': (3, 8), 'D': (4, 9)}
Using lists like this is a bit annoying - you can improve on the design by making a new type that stores data by name, instead of index:
from dataclasses import dataclass
@dataclass
class Stock:
held: int
max: int
books = {
"Fiction" : Stock(0, 30),
"Non-Fiction": Stock(0, 20),
"Science" : Stock(0, 15),
"History" : Stock(0, 25),
}
for category, stock in books.items():
print(f"Category: {category}, Stock: {stock.held}/{stock.max}")
That way, you retrieve the max value by saying books[selected_genre].max, instead of books[selected_genre][1] or whichever magic number you chose for that
You can even explicitly clarify which value you're setting, when you make a Stock instance:
Stock(held = 0, max = 30)
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.