-3

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
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

You can use a simple nested loop:

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

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
mozway
  • 194,879
  • 13
  • 39
  • 75
0

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
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126