Search code examples
pythonpython-3.xdefaultdict

How to extract values from defaultdict with nested list values?


I have a defaultdict with nested list values and I need to extract the values as shown in the output.

dd = defaultdict(list)
print(dd)

Input:

defaultdict(<class 'list'>, {
'1': [[['Peter', '100'], ['John', '200'], ['Carlos', '150'], ['Rick', '25']], ['HR']], 
'2': [[['Albert', '200']], ['Travel']], 
'3': [[['Mick', '300']], ['IT']]
})

output:

1,Peter,100,HR
1,John,200,HR
1,Carlos,150,HR
1,Rick,25,HR
2,Albert,200,Travel
3,Mick,300,IT

Solution

  • You need to iterate on your list value to get desired output as:

    for k, v in dd.items():
        for vv in v[0]:
           print(','.join([k, vv[0], vv[1], v[1][0]]))
    

    Here v[0] is your list of names and number i.e. [['Peter', '100']...], and v[1] is the list of department i.e. ['HR'].

    Above code will print:

    1,Peter,100,HR
    1,John,200,HR
    1,Carlos,150,HR
    1,Rick,25,HR
    2,Albert,200,Travel
    3,Mick,300,IT