Search code examples
pythonpython-3.xdefaultdict

Double Nesting defaultdict


Poked around but couldn't figure it out, probably a very simple solution but please help me understand.

Source (sample.txt):

1,1,2,3
2,3,2,4,4

This:

import csv
from collections import defaultdict

input = "sample.txt"

with open(input) as f:
    r = csv.reader(f)
    d = defaultdict(list)
    rlabel = 1

    for row in r:
        d[rlabel].append(row)
        rlabel += 1

print(d)

Gets This:

defaultdict(<class 'list'>, {1: [['1', '1', '2', '3']], 2: [['2', '3', '2', '4', '4']]})

Why are there double brackets around my lists?


Solution

  • Why are there double brackets around my lists?

    Your code works exactly as expected. The key point is the usage of extend and append.

    • append adds the parameter you passed as a single element. Due to a list is an object and your defaultdict class is list, so the list is appended as a list of lists.

    • extend method iterate in the input and extend the original list by adding all elements from an iterable.

    So, in this case, if you want to add a single list to your defaultdict you should use list.extend method. And your output will be:

    defaultdict(<class 'list'>, {1: ['1', '1', '2', '3'], 2: ['2', '3', '2', '4', '4']})