One-step initialization of defaultdict that appends to list?

后端 未结 5 775
情话喂你
情话喂你 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:37

    What you're apparently missing is that defaultdict is a straightforward (not especially "magical") subclass of dict. All the first argument does is provide a factory function for missing keys. When you initialize a defaultdict, you're initializing a dict.

    If you want to produce

    defaultdict(, {'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]})
    

    you should be initializing it the way you would initialize any other dict whose values are lists:

    d = defaultdict(list, (('a', [1, 2]), ('b', [2, 3]), ('c', [3]), ('d', [4])))
    

    If your initial data has to be in the form of tuples whose 2nd element is always an integer, then just go with the for loop. You call it one extra step; I call it the clear and obvious way to do it.

提交回复
热议问题