#πŸ”’ Combining Multiple Dictionaries into a single Dictionary

49 messages Β· Page 1 of 1 (latest)

bleak oyster
#
# 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!
bitter roostBOT
#

@bleak oyster

Python help channel opened

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.

bleak oyster
#

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".

bleak oyster
#

Somewhat.

#

I have definitely heard of lists and tuples.

mossy totem
bleak oyster
#
books = {
    Fiction["1"] = [30, 0]
    Non-Fiction["2"] = [20, 0]
    Science["3"] = [15, 0]
    History["4"] = [25, 0]
    }```

Is this correct?
mossy totem
#

tuples its ()

#

dict its {} and : btw key,value pairs

#

just {} would be set, like {1,2,3,4}

bleak oyster
#

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.

bleak oyster
grand seal
#

when you make a list, you put [] around the elements of the list

bleak oyster
grand seal
#

kind of

#

the keys in the first one are correct, the values in the second one are correct

bleak oyster
#
books = {
    "Fiction": [30, 0]
    "Non-Fiction": [20, 0]
    "Science": [15, 0]
    "History": [25, 0]
    }```

This, then?
grand seal
#

yep, one last step now

#

key value pairs in a dictionaries are separate by commas

bleak oyster
#

As in, a comma after the []?

grand seal
#

yep

bleak oyster
#

"Fiction": [30, 0],

grand seal
#

yes

bleak oyster
#

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.

grand seal
bleak oyster
pale canyon
bitter roostBOT
dark nest
#

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)

bitter roostBOT
#
Python help channel closed for inactivity

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.