Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify list to dictionary in Python

How convert a list of email addresses to a dictionary, where the keys are the usernames, and the values are the respective domains.

I did my code, but it did not give me right answer. What am I doing wrong? How to receive 3 keys and 3 values?

list1="harry@abc.com , larry@abc.ca , sally@abc.org "
list2=list1.split("@",3)
print({list2[i]:list2[i+1] for i in range(0,len(list2),2)})

>> {'harry': 'abc.com , larry', 'abc.ca , sally': 'abc.org '} 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The first issue here is that the value of list1 is a string, not a list.
Your code should look like this:

list1 = ["harry@abc.com", "larry@abc.ca", "sally@abc.org"]
dict1 = {}
for email_address in list1:
    name_and_domain = email_address.split("@")
    name = name_and_domain[0]
    domain = name_and_domain[1]
    dict1[name] = domain

or if you must keep the value of list1 as a string, you can convert it to a list by splitting it at each , like this:

string1 = "harry@abc.com,larry@abc.ca,sally@abc.org"
list1 = string1.split(',')
dict1 = {}
for email_address in list1:
    name_and_domain = email_address.split("@")
    name = name_and_domain[0]
    domain = name_and_domain[1]
    dict1[name] = domain
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading