从嵌套列表创建嵌套字典

时间:2013-05-22 17:16:46

标签: python list dictionary nested

从嵌套列表中:

lst = [['h2o', '2938', 'v1'], ['co2', '2492', 'v1'], ['co2', '2492', 'v2'], ['o3', '780', 'v2'], ['o3', '1140', 'v2']]

我想创建一个嵌套字典:

t1 = {h2o:{2938:['v1']}, co2:{2492:['v1','v2']}, o3:{780:['v2'], 1140:['v2']}}

是否可以使用字典理解来完成此操作?是否有更好的数据结构类型来保存这些关系?

提前致谢!

1 个答案:

答案 0 :(得分:3)

from collections import defaultdict
lst = [['h2o', '2938', 'v1'], ['co2', '2492', 'v1'], ['co2', '2492', 'v2'], ['o3', '780', 'v2'], ['o3', '1140', 'v2']]
dd = defaultdict(lambda: defaultdict(list))
for a, b, c in lst:
    dd[a][b].append(c)    

>>> dd
defaultdict(<function <lambda> at 0xb6fb087c>, {'h2o': defaultdict(<type 'list'>, {'2938': ['v1']}), 'co2': defaultdict(<type 'list'>, {'2492': ['v1', 'v2']}), 'o3': defaultdict(<type 'list'>, {'1140': ['v2'], '780': ['v2']})})