0

There is a list of email id and need to add key "email" to every elements in a list. Email list:

user = ["test@xyz.com","check@xyz.com"]

Here email key is to be added and output should be as. [{'email': 'test@xyz.com'}, {'email': 'check@xyz.com'}]

For this,

email_object = {}
email_list = []
user = ["test@xyz.com","check@xyz.com"]

for i in user:
    email_object["email"] = i
    email_list.append(email_object)
print(email_list)

Result:

 [{'email': 'check@xyz.com'}, {'email': 'check@xyz.com'}]

Only last email address in a list is shown in a result. How to show output result as :

[{'email': 'test@xyz.com'}, {'email': 'check@xyz.com'}]
Himal Acharya
  • 836
  • 4
  • 14
  • 24

1 Answers1

1

You can use list-comprehension like the following:

users = ["test@xyz.com","check@xyz.com"]
res = [{"email": v} for v in users]

This will results in:

[{'email': 'test@xyz.com'}, {'email': 'check@xyz.com'}]

The problem your experiencing using your code is the fact that you append the same copy of the email_object to the list while changing it.

You can modify your code the following to make it work as expected:

...
email_list.append(email_object.copy())
...
David
  • 8,113
  • 2
  • 17
  • 36