# 如何在Python中创建数组的嵌套DICRATE

mytable = [
[117, 12, 'wer'],
[117, 23, 'hgr'],
[42, 33, 'hgj'],
[910, 27, 'sfr'],
[910, 31, 'mhn'],
[910, 98, 'wlc'],
[453, 11, 'nlj'],
[453, 65, 'nfg'],
[312, 17, 'fyg'],
[312, 44, 'gfn']
]


mytree = {
117: [[12, 'wer'], [23, 'hgr']],
42 : [[33, 'hgj']],
910: [[27, 'sfr'], [31, 'mhn'], [98, 'wlc']],
453: [[11, 'nlj'], [65, 'nfg']],
312: [[17, 'fyg'], [44, 'gfn']]
}


This does not work:

mytree = {}

for arr in mytable:


## 推荐答案

mytree = {}

for (k, *arr) in mytable:
mytree.setdefault(k, []).append(arr)


>>> mytree
{117: [[12, 'wer'], [23, 'hgr']],
42: [[33, 'hgj']],
910: [[27, 'sfr'], [31, 'mhn'], [98, 'wlc']],
453: [[11, 'nlj'], [65, 'nfg']],
312: [[17, 'fyg'], [44, 'gfn']]}


collections模块中的defaultdict:

from collections import defaultdict

mytree = defaultdict(list)

for (k, *arr) in mytable:
mytree[k].append(arr)


>>> mytree
defaultdict(list,
{117: [[12, 'wer'], [23, 'hgr']],
42: [[33, 'hgj']],
910: [[27, 'sfr'], [31, 'mhn'], [98, 'wlc']],
453: [[11, 'nlj'], [65, 'nfg']],
312: [[17, 'fyg'], [44, 'gfn']]})