0

I want to extract all the words that are before "indices" (i.e ForeverTrophyless, NoPainNoGame, Prize) and put em all inside a list. How Can I do that?

foo = '[{"text":"ForeverTrophyless","indices":[0,18]},{"text":"ForeverTrophyless","indices":[19,37]},{"text":"Prize","indices":[38,56]},{"text":"ForeverTrophyless","indices":[57,75]},{"text":"NoPainNoGame","indices":[76,94]},{"text":"ForeverTrophyless","indices":[95,113]},{"text":"ForeverTrophyless","indices":[114,132]}]'

Python2.7

Pycharm Ubuntu 14.04

2
  • 1
    [x['text'] for x in foo]. Also, there's no such thing like "before" in dictionaries, because they're unordered. Commented Jul 10, 2014 at 17:58
  • @vaultah Sorry friend I forgot the ' ' in my question, foo is a string Commented Jul 10, 2014 at 18:00

2 Answers 2

3

You can use ast.literal_eval to turn that string into a list of dictionaries.

foo = '[{"text":"ForeverTrophyless","indices":[0,18]},{"text":"ForeverTrophyless","indices":[19,37]},{"text":"Prize","indices":[38,56]},{"text":"ForeverTrophyless","indices":[57,75]},{"text":"NoPainNoGame","indices":[76,94]},{"text":"ForeverTrophyless","indices":[95,113]},{"text":"ForeverTrophyless","indices":[114,132]}]'

import ast
l = ast.literal_eval(foo)

l is now:

[{'indices': [0, 18], 'text': 'ForeverTrophyless'},
 {'indices': [19, 37], 'text': 'ForeverTrophyless'},
 {'indices': [38, 56], 'text': 'Prize'},
 {'indices': [57, 75], 'text': 'ForeverTrophyless'},
 {'indices': [76, 94], 'text': 'NoPainNoGame'},
 {'indices': [95, 113], 'text': 'ForeverTrophyless'},
 {'indices': [114, 132], 'text': 'ForeverTrophyless'}]

Then use a list comprehension

[i['text'] for i in l]

Result

['ForeverTrophyless', 'ForeverTrophyless', 'Prize', 'ForeverTrophyless', 'NoPainNoGame', 'ForeverTrophyless', 'ForeverTrophyless']
Sign up to request clarification or add additional context in comments.

Comments

2

foo appears to be a valid serialized JSON object. You can parse it with json.loads and then retrieve all text fields inside a list comprehension:

In [8]: from json import loads

In [9]: [x['text'] for x in loads(foo)]
Out[9]: 
['ForeverTrophyless',
 'ForeverTrophyless',
 'Prize',
 'ForeverTrophyless',
 'NoPainNoGame',
 'ForeverTrophyless',
 'ForeverTrophyless']

1 Comment

Yes, is part of a JSON object. Thanks for your help, You're right!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.