Reputation: 237
I'm currently working on a script that'll be working with Youtubes API. I'm still learning how to correctly parse using Python, but am a little lost on what method to take for something like this.
I have this string:
[{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]
I need to take that, and turn it in to this:
Video Blogging, blogging, stuff, Videos
What would be the best approach to solve this? Any help is appreciated, thanks!
Upvotes: 0
Views: 89
Reputation: 24788
For this specific case, you can use a list comprehension:
list_of_stuff = [
{'term': u'Video Blogging', 'scheme': None, 'label': None},
{'term': u'blogging', 'scheme': None, 'label': None},
{'term': u'stuff', 'scheme': None, 'label': None},
{'term': u'Videos', 'scheme': None, 'label': None}
]
parsed_string = ', '.join([d['term'] for d in list_of_stuff])
Upvotes: 0
Reputation: 24670
>>> l = [{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]
>>> [a.get('term') for a in l]
[u'Video Blogging', u'blogging', u'stuff', u'Videos']
and if you want to get the items as a comma-delimited string, use:
>>> ', '.join(a.get('term') for a in l)
u'Video Blogging, blogging, stuff, Videos'
I used a.get('term')
instead of a['term']
to avoid a KeyError
for items without a term
key.
Upvotes: 4
Reputation: 40374
It should be something like this:
>>> l = [{'term': u'Video Blogging', 'scheme': None, 'label': None}, {'term': u'blogging', 'scheme': None, 'label': None}, {'term': u'stuff', 'scheme': None, 'label': None}, {'term': u'Videos', 'scheme': None, 'label': None}]
>>> ', '.join([d['term'] for d in l])
u'Video Blogging, blogging, stuff, Videos'
Upvotes: 1