Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - how do i create a list when retrieving a list from a dictionary

I am looking up a set of email addresses grouped together in a dictionary using the get() function

the get function returns

['[“one.yahoo.com”,”two.yahoo.com”,"three.yahoo.com"]']

I have tried several methods to remove the single quotes so that I end up with a list like this

email = [ [“one.yahoo.com”,”two.yahoo.com”,"three.yahoo.com"] ]

the dictionary looks like this

dict= { 'Warehouse':'[“[email protected]”,”[email protected]”,”[email protected]”]', 'Bottling':'[“one.yahoo.com”,”two.yahoo.com”,"three.yahoo.com"]'}

question from:https://stackoverflow.com/questions/65949659/how-do-i-create-a-list-when-retrieving-a-list-from-a-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

import ast # This contains a function to convert str to list
email = ['["one.yahoo.com", "two.yahoo.com", "three.yahoo.com"]']
email = str(email) # Converts to str type.
email = email.replace("'", "") # Replaces the apostrophes with blanks.
email = ast.literal_eval(email) # Converts to list. 
print(email)

Output is:

[["one.yahoo.com", "two.yahoo.com", "three.yahoo.com"]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...