簡體   English   中英

Python 3:如何創建一個包含多個字典的字典,其中鍵也有多個值?

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

我一直在為庫存類型系統編寫代碼,一直以來我一直在使用set()只是為了意識到它里面的字符串/數字沒有順序。

所以我將再次重寫我的代碼並使用dict()代替。 但是,我仍然不知道如何采取這種方法。 我希望我的輸出是這樣的:

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

注意:我不確定它是括號還是大括號我應該用作示例

簡單的說:

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

我的代碼:

https://pastebin.com/gu5DJX5K現在已經搜索了一段時間,但找不到我可以應用到我的代碼的類似示例。

字典也沒有排序——Python 中的集合和字典都使用哈希表,它們不保留排序。 如果您需要排序,您應該使用類或列表。

如果您無論如何都使用字典,那么字典中的值是另一個字典完全沒問題。 要為一個鍵設置多個值,請將這些值存儲在一個列表中,與該鍵對應的值將是該列表(或者,如果您不需要排序,則是一個集合)。

它看起來像:

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

但是,我強烈建議您不要在任何事情上都使用字典。 類使用起來要干凈得多。 我會推薦一些類似的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM