我想編寫一個代碼來創建一個表,該表將水果映射到不同籃子中的數量的字典。從表創建字典 - python
table = [['Fruit', 'Basket1', 'Basket2', 'Basket3'],
['Apples', 4, 5, 6],
['Bananas', 7, 8, 10],
['Oranges', 8, 9, 2]]
Expected dictionary: {'Apples': {'Basket1':[4],'Basket2':[5],'Basket3':[6]}, 'Bananas':{'Basket1':[7],'Basket2':[8],'Basket3':[10]}, 'Oranges':{'Basket1':[8],'Basket2':[9],'Basket3':[2]}}
Expected Output: [Apples][Basket1]= 4
以下是我到目前爲止。我知道最後兩行沒有意義,但我很難弄清楚如何關閉這一行。
basket = [y for y in table[0] if y!='Fruit']
Quantity=[y[1:4] for y in table if y[0]!='Fruit']
Fruit = [y[0] for y in table if y[0]!='Fruit']
a = dict(zip(Fruit, Quantity))
b = dict(zip(a,Basket)
b
你的「預期」字典不是詞典。它似乎是一個字典清單。另外,你的桌子是什麼?當然不是有效的python。 – Alexander
粘貼報價是否很難...... –
我的歉意。我的表是列表的列表,但只是想將其轉換爲字典 – GenXeral