One-step initialization of defaultdict that appends to list?

后端 未结 5 776
情话喂你
情话喂你 2021-02-19 01:09

It would be convenient if a defaultdict could be initialized along the following lines

d = defaultdict(list, ((\'a\', 1), (\'b\', 2), (\'c\', 3), (         


        
5条回答
  •  攒了一身酷
    2021-02-19 01:35

    >>> kvs = [(1,2), (2,3), (1,3)]
    >>> reduce(
    ...   lambda d,(k,v): d[k].append(v) or d,
    ...   kvs,
    ...   defaultdict(list))
    defaultdict(, {1: [2, 3], 2: [3]})
    

提交回复
热议问题