Search code examples
python-3.xdictionarysetkey-valueinventory

Python 3: How to create a Dictionary with multiple dictionaries in it and where the keys also have multiple values?


I've been writing a code for an Inventory-type system and all this time I've been using set() only to realize that strings/numbers inside it are not in order.

So I'll be rewriting my code again and will use dict() instead. However, i still have no idea how to take this approach. I'd like my output to be something like this:

{'fruits':{'apple':{20, 15}},{'orange':{10, 12}}}, {'veggies':{'cucumber':{30, 20}}, {'cabbage':{40, 15}}}}

Note: I'm not sure if it's brackets or braces i should use as examples

Simply put:

Fruits & Veggies - Inventory Names
Apple and Orange - Items in the Inventory
10, 30 & 40 - Number of stocks of the item
12, 20,& 15 - Amount of each item

My code:

https://pastebin.com/gu5DJX5K Been searching for a while now and can't find similar example of codes i can apply to mine.


Solution

  • Dictionaries are not ordered either - both sets and dictionaries in Python use hash tables, which do not preserve ordering. If you need ordering, you should use classes or lists.

    If you use dictionaries anyway, it's perfectly fine for the values in a dictionary to be another dictionary. To have multiple values for a key, store the values in a list, and it the value corresponding to that key will be the list (or if you don't need ordering, a set).

    It would look something like:

    {"fruits" => {"apple" => [20, 15]
                  "orange" => [10, 12]}
     "veggies" => {"cucumber" => [30, 20]
                   "cabbage" => [40, 15]}}
    

    However, I strongly discourage you from using dictionaries for everything. Classes are just much cleaner to use. I would recommend something along the lines of:

    class Inventory:
        def __init__(self, fruits, veggies):
            self.fruits = fruits # list of Items
            self.veggies = veggies # another list of Items
    
    class Item:
        def __init__(self, name, stock, amount):
            self.name = name # a string
            self.stock = stock # an int
            self.amount = amount # an int