Home > OS >  Modify list to dictionary in Python
Modify list to dictionary in Python

Time:03-08

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="[email protected] , [email protected] , [email protected] "
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 '} 

CodePudding user response:

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

list1 = ["[email protected]", "[email protected]", "[email protected]"]
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 = "[email protected],[email protected],[email protected]"
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
  • Related