i have list which has the following words stored . How Can i seperate the sentence inside the [ and ] for example in dash[0] what i need to sperate is The Sunday Profile: Panth meets Wealth from the rest. I want to do that in each group and store it . -
dash = ['{"Headlines": ["The Sunday Profile: Panth meets Wealth"]}\n', '{"Headlines": ["Wage no bar"]}\n']
i have tried-
for line in f:
text = line
print(text)
but that prints only the last line
CodePudding user response:
from ast import literal_eval
dash = ['{"Headlines": ["The Sunday Profile: Panth meets Wealth"]}\n',
'{"Headlines": ["Wage no bar"]}\n']
for i in dash:
print(literal_eval(i)["Headlines"])
CodePudding user response:
I would recommend that in the future you follow StackOverflow's guidance on asking a good question. You should also be sure to provide a minimal, reproducible example.
With that said, assuming the values in the dash
list are always json and there is always one headline, you could use a list comprehension to get a new list of all headlines.
import json
dash = ['{"Headlines": ["The Sunday Profile: Panth meets Wealth"]}\n', '{"Headlines": ["Wage no bar"]}\n']
headlines = [json.loads(x)["Headlines"][0] for x in dash]
The new variable headlines
would have all of the items you are looking for. If Headlines
from the dash
list can have more than one value, I'd recommend just leaving them as lists and dropping the [0]
index from the stated solution.
CodePudding user response:
Create a function that converts the string to a dictionary and returns the first item of the value
import json
def get_first_item(s):
return json.loads(s).values()[0][0]
Then map the function to the list
for line in map(get_first_item, dash):
print(line)
gives
The Sunday Profile: Panth meets Wealth
Wage no bar