Skip to main content
 首页 » 编程设计

python之从表创建字典之python

2025年02月15日8think

我想编写一个代码来从一个表中创建一个字典,该表将水果映射到不同篮子中水果数量的字典。

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 

请您参考如下方法:

假设您不关心表格标题行,您可以使用字典理解并枚举表格行:

>>> {row[0]: {'Basket{}'.format(n): [v] for n, v in enumerate(row[1:], start=1)} 
     for row in table[1:]} 
{'Apples': {'Basket1': [4], 'Basket2': [5], 'Basket3': [6]}, 
 'Bananas': {'Basket1': [7], 'Basket2': [8], 'Basket3': [10]}, 
 'Oranges': {'Basket1': [8], 'Basket2': [9], 'Basket3': [2]}} 

如果您必须匹配 header ,那么这种方法应该有效:

headers = table[0][1:] 
{row[0]: {header: [v] for header, v in zip(headers, row[1:])} 
          for row in table[1:]}