0

从嵌套列表中:

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

是否可以使用字典理解来做到这一点?是否有更好的数据结构类型来保存这些关系?

提前致谢!

4

1 回答 1

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']})})
于 2013-05-22T17:19:40.900 回答