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

Question:

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?

Asked By: init200

||

Answers:

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
Answered By: S.B
    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.

Answered By: ghost_ds
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.