将列表列表分解为字典

Breaking down list of list into dictionaries

我有一个list列表,s,就是在Fruit上查询一个数据库的结果,item[0]是水果的名字,item[1]是是不是不是果实有籽,item[2]是能不能吃

s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

由于我的实际列表要大得多,所以我想要一个非常简单的方法来 reference/return 这些值。例如,print my_dict['Apple']['Seeds'] 会产生 Yes

我认为我最好的选择是创建一个字典,但我正在寻找关于这是否是一个好方法以及如何做到这一点的建议。

我开始编写一些代码,但不确定如何获得第二组 headers,因此我的示例使用索引。

my_dict =  {t[0]:t[1:] for t in s}

print my_dict['Apple'][0]
fruit_map = {
    fruit: {'Seeds': seeds, 'Edible': edible} for fruit, seeds, edible in s}

如果第二组键永远不变,最好定义一个带有字段的适当对象。这可能看起来有点矫枉过正或冗长,但总有 collections.namedtuple 可以提供帮助。

namedtuple 从字段名称列表创建一个新的 class。那 class 也支持被列表初始化。要使用您的示例:

import collections

Fruit = collections.namedtuple('Fruit', ['name', 'seeds', 'edible'])

这样,您可以轻松地从列表中创建 Fruit 个对象:

f = Fruit('Apple', True, False)
# Or, if you already have a list with the values
params = ['Apple', True, False]
f = Fruit(*params)

print f.seed

因此您可以非常简单地创建水果列表:

s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

fruits = [Fruit(*l) for l in s]

你真的需要一个由某个字段索引的字典,这没什么不同:

s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

fruit_dict = {l[0]: Fruit(*l) for l in s}    
print(fruit_dict['Apple'].seeds)

namedtuples 在将值列表转换为更易于使用的对象时非常方便(例如读取 CSV 文件时,这与您所要求的情况非常相似)。

import copy

def list_to_dict(lst):
    local = copy.copy(lst) # copied lst to local
    fruit = [i.pop(0) for i in local] # get fruit names

    result = {}
    for i in range(len(local)):
        result[fruit[i]] = local[i]
    return result

这returns你想要的词典。