Sample code below:
JavaScript
x
22
22
1
list_of_dict = list([{'id':1,'amt':1},{'id':2,'amt':20},{'id':3,'amt':30}])
2
3
def fooFunc(a,b):
4
rows = [] ## list object
5
for e in range(b):
6
new = a.copy()
7
new['amt'] = a['amt'] / b
8
rows.append(new) ## using append()
9
return rows
10
11
output=[]
12
for i in list_of_dict:
13
idnmbr = i['id']
14
if idnmbr == 2:
15
output.append(fooFunc(i,2))
16
elif idnmbr == 3:
17
output.append(fooFunc(i,3))
18
else:
19
output.append(i)
20
21
print(output)
22
Output:
JavaScript
1
2
1
[{'id': 1, 'amt': 1}, [{'id': 2, 'amt': 10.0}, {'id': 2, 'amt': 10.0}], [{'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]]
2
Wan’t to get rid of [square brackets] i.e. [{‘id’: 2, ‘amt’: 10.0}, {‘id’: 2, ‘amt’: 10.0}] that is being appended from the function call that returns results/rows as a list.
Tried converting the function call return to a dictionary object, but results are not as expected.
JavaScript
1
20
20
1
def fooFuncDict(a,b):
2
rows = {} ## dictionary object
3
for e in range(b):
4
new = a.copy()
5
new['amt'] = a['amt'] / b
6
rows.update(new) ## using update()
7
return rows
8
9
output=[]
10
for i in list_of_dict:
11
idnmbr = i['id']
12
if idnmbr == 2:
13
output.append(fooFuncDict(i,2))
14
elif idnmbr == 3:
15
output.append(fooFuncDict(i,3))
16
else:
17
output.append(i)
18
19
print(output)
20
Output:
JavaScript
1
2
1
[{'id': 1, 'amt': 1}, {'id': 2, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]
2
Advertisement
Answer
I believe you need list.extend
Ex:
JavaScript
1
11
11
1
output=[]
2
for i in list_of_dict:
3
idnmbr = i['id']
4
if idnmbr == 1:
5
output.append(i)
6
else:
7
output.extend(fooFunc(i,idnmbr))
8
9
print(output)
10
# [{'id': 1, 'amt': 1}, {'id': 2, 'amt': 10.0}, {'id': 2, 'amt': 10.0}, {'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]
11