从表创建字典 - python

时间:2017-08-25 04:40:26

标签: python python-3.x

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

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

3 个答案:

答案 0 :(得分:1)

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

>>> {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]}}

如果必须匹配标题,则此方法应该有效:

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

答案 1 :(得分:0)

table = [['Fruit', 'Basket1', 'Basket2', 'Basket3'],
        ['Apples', 4, 5, 6],
        ['Bananas', 7, 8, 10],
        ['Oranges', 8, 9, 2]]
m={}                                      
for i in range(1,len(table)):
    if table[i][0] not in m:
        m[table[i][0]]={}
    for j in range(1,len(table[i])):
        #print m[table[i][0]]
        if table[i][j] not in m[table[i][0]]:
            m[table[i][0]][table[0][j]]=table[i][j]
print m

答案 2 :(得分:0)

您可以将headerrows数据分开,zip()将标题与row分开,例如:

In []:
header, *rows = table
{k: dict(v) for row in rows for (_, k), *v in [list(zip(header, row))]}

Out[]:
{'Apples': {'Basket1': 4, 'Basket2': 5, 'Basket3': 6},
 'Bananas': {'Basket1': 7, 'Basket2': 8, 'Basket3': 10},
 'Oranges': {'Basket1': 8, 'Basket2': 9, 'Basket3': 2}}