Skip to content
Advertisement

How to convert a list into a dictionary object and return from function? [closed]

Sample code below:

list_of_dict = list([{'id':1,'amt':1},{'id':2,'amt':20},{'id':3,'amt':30}])

def fooFunc(a,b):
    rows = []                       ## list object
    for e in range(b):
        new = a.copy()
        new['amt']  = a['amt'] / b
        rows.append(new)            ## using append()
    return rows

output=[]
for i in list_of_dict:
    idnmbr = i['id']
    if idnmbr == 2:
        output.append(fooFunc(i,2))
    elif idnmbr == 3:
        output.append(fooFunc(i,3))
    else:
        output.append(i)

print(output)

Output:

[{'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}]]

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.

def fooFuncDict(a,b):
    rows = {}                 ## dictionary object
    for e in range(b):
        new = a.copy()
        new['amt']  = a['amt'] / b
        rows.update(new)      ## using update()
    return rows

output=[]
for i in list_of_dict:
    idnmbr = i['id']
    if idnmbr == 2:
        output.append(fooFuncDict(i,2))
    elif idnmbr == 3:
        output.append(fooFuncDict(i,3))
    else:
        output.append(i)

print(output)

Output:

[{'id': 1, 'amt': 1}, {'id': 2, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]

Advertisement

Answer

I believe you need list.extend

Ex:

output=[]
for i in list_of_dict:
    idnmbr = i['id']
    if idnmbr == 1:
        output.append(i)
    else:
        output.extend(fooFunc(i,idnmbr))

print(output)
# [{'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}]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement