0

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

user = ["[email protected]","[email protected]"]

Here email key is to be added and output should be as. [{'email': '[email protected]'}, {'email': '[email protected]'}]

For this,

email_object = {}
email_list = []
user = ["[email protected]","[email protected]"]

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

Result:

 [{'email': '[email protected]'}, {'email': '[email protected]'}]

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

[{'email': '[email protected]'}, {'email': '[email protected]'}]
Himal Acharya
  • 836
  • 4
  • 14
  • 24

1 Answers1

1

You can use list-comprehension like the following:

users = ["[email protected]","[email protected]"]
res = [{"email": v} for v in users]

This will results in:

[{'email': '[email protected]'}, {'email': '[email protected]'}]

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