[英]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.如何将 email 地址列表转换为字典,其中键是用户名,值是各自的域。
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?
如何接收 3 个键和 3 个值?
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 '}
The first issue here is that the value of list1
is a string, not a list.这里的第一个问题是
list1
的值是一个字符串,而不是一个列表。 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:或者,如果您必须将
list1
的值保留为字符串,则可以通过在每个处拆分它来将其转换为列表,
如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.