Search code examples
pythondefaultdict

Remove the function and command from the output


I have trying out defaultdict with lamba function. However, I could not get the output I want. I will demonstrate with more details. Below is my code:

from collections import defaultdict

the_list = [
    ('Samsung', 'Handphone', 10), 
    ('Samsung', 'Handphone', -1), 
    ('Samsung', 'Tablet', 10),
    ('Sony', 'Handphone', 100)
]

d = defaultdict(lambda: defaultdict(int))

for brand, thing, quantity in the_list:
    d[brand][thing] += quantity

My result is:

defaultdict(<function <lambda> at 0x02715C70>, {'Sony': defaultdict(<type 
'int'>, {'Handphone': 100}), 'Samsung': defaultdict(<type 'int'>, {'Handphone': 
9, 'Tablet': 10})})

I want my result to be this:

{
    'Samsung': {
        'Handphone': 9, 
        'Tablet': 10
    },
    'Sony': {
        'Handphone': 100
    }
}

How am I supposed to do remove the defaultdict(<function <lambda> at 0x02715C70>, {'Sony': defaultdict(<type int'>, to achieve my desired output. Thank you!


Solution

  • Just convert each defaultdict back to a regular dict, you can do it easily using dict comprehension:

    { k:dict(v) for k,v in d.items() }
    #output
    {'Sony': {'Handphone': 100}, 'Samsung': {'Tablet': 10, 'Handphone': 9}}