Home > Enterprise >  How do I pass multiple dictionary items into a function and return a list?
How do I pass multiple dictionary items into a function and return a list?

Time:09-09

API called is made using the variable results:

results = service.users().messages().list(userId='me', labelIds=['INBOX', 'UNREAD']).execute()

A dictionary is returned:

{'messages': [{'id': '182f01f99c14b435', 'threadId': '182ef213b5174c23'}, {'id': '182f0120c66cc135', 'threadId': '182ef214b5174c23'}], 'resultSizeEstimate': 2}

Passing blank list and results into a function:

message_list = []


def return_message(message_list, results):
    messages_ = results.get('messages', [])

    for message in messages_:
        for k,v in message.items():
            message_list.append(message)
            return message_list

Run the function but I am only able to return 1 appended message:

return_message(message_list, results)
print(message_list)

[{'id': '182f01f88c14b435', 'threadId': '182ef213b5154c23'}]

How do I return the entire results passed in at the beginning from the function so it's all been appended onto message_list?

CodePudding user response:

Because you're returning right after appending to your list. return terminates the function. So in first iteration you add one item and then the function returnes.

change it to:

def return_message(message_list, results):
    messages_ = results.get("messages", [])

    for message in messages_:
        for k, v in message.items():
            message_list.append(message)
            # return message_list
    return message_list

CodePudding user response:

    for message in messages_:
        for k,v in message.items():
            message_list.append(message)
            return message_list

An explicit return statement immediately terminates a function execution and sends the return value back to the caller code. Since the return statement is inside the for loop, it terminates in the first iteration of the loop.

To get the complete list, the return statement should be outside the for loop as such:

    for message in messages_:
        for k,v in message.items():
            message_list.append(message)
    return message_list

A second point to note here is that the nested for loop does not really do anything here (given this is the complete code). Therefore calling the .append() method here, inserts the same message twice in the list.

You can solve this issue by having a conditional statement to check or by completely removing the second for loop.

Final Answer

    for message in messages_:
        message_list.append(message)
    return message_list

Additionally,

You could simply use the extend() method or even concatenate the lists since bot of the variables are lists.

Using extend()

message_list.extend(messages_)

Concatenating

message_list  = messages_

Both of which would give the same result.

  • Related