在字典中存储列表列表

时间:2019-07-04 13:27:32

标签: python python-3.x list dictionary

我试图在Python 3中存储然后显示一些数据。我相信我试图存储/使用的数据类型是列表的决定。但我不确定100%。我想同时将每个变量打印为单独的实体。我的假设是,这将需要for循环的组合

我将给出一个简化的示例,希望会对您有所帮助。

我在超市有关于水果的信息。

- Tesco 
  - Apples  
    - Cooking Apples
    - Granny Smiths
    - Gala
  - Oranges
    - Blood Orange
    - Mandarin Orange
- Asda 
  - Pineapples 
    - Cavendish
    - Burro 
  - Oranges    
    - Blood Orange
    - Tangerine
- Lidl 
  - Apples 
    - Gala 
    - Cooking Apples
  - Mangoes
    - Chaunsa
    - Badami
    - Kesar

我想存储此信息,然后以类似格式显示回去。

3 个答案:

答案 0 :(得分:3)

是的,您的示例如下所示:

data = {'Tesco': {'Apples': ['Cooking Apples',
                             'Granny Smiths',
                             'Gala'],
                  'Oranges': ['Blood Orange',
                              'Mandarin Orange']
                 },
        'Asda': {'Pineapples': ['Cavendish',
                                'Burro'],
                 'Oranges': ['Blood Orange',
                             'Tangerine']
                 },
        'Lidl': {'Apples': ['Cooking Apples',
                            'Gala'],
                 'Mangoes': ['Chaunsa',
                             'Badami',
                             'Kesar']}
        }

但是,正如评论中所述,它实际上取决于您要对这些数据执行的操作。

答案 1 :(得分:0)

data = {}
data["Tesco"] = {}
data["Tesco"]["Apples"] = ["Cooking Apples", "Granny Smiths","Gala"]
data["Tesco"]["Oranges"] = ["Blood Orange", "Mandarin Orange"]

data["Asda"] = {}
data["Asda"]["Pineapples "] = ["Cavendish", "Burro"]
data["Asda"]["Oranges"] = ["Blood Orange", "Tangerine"]

data["Lidl"] = {}
data["Lidl"]["Apples  "] = ["Gala ", "Cooking Apples"]
data["Lidl"]["Mangoes"] = ["Chaunsa", "Badami","Kesar"]

print(data)

答案 2 :(得分:0)

对于那些想知道我的问题的完整答案的人如下:

要输入数据: 归功于“ zipa”。

data = {'Tesco': {'Apples': ['Cooking Apples',
                             'Granny Smiths',
                             'Gala'],
                  'Oranges': ['Blood Orange',
                              'Mandarin Orange']
                 },
        'Asda': {'Pineapples': ['Cavendish',
                                'Burro'],
                 'Oranges': ['Blood Orange',
                             'Tangerine']
                 },
        'Lidl': {'Apples': ['Cooking Apples',
                            'Gala'],
                 'Mangoes': ['Chaunsa',
                             'Badami',
                             'Kesar']}
        }

并得到它:

    for Supermarket in data:
...     print(Supermarket)
...     for fruit in data[Supermarket]:
...             print(fruit)
...             for type in data[Supermarket][fruit]:
...                     print(type)