Ad
How Do You Split A Dictionary String Value In A List Of Dictionaries To Add A New Dictionary Item?
I have a list of dictionaries and in each list there is a key called text with a string value. To each dictionary I want to add a new item which is called first_word which is a split of the string of text to obtain the the code.
For example if I have:
alist =[{'id':1, 'text':'Dogs are great'},
{'id':2, 'text':'Cats are great'},
'id':3, 'text':'Fish are smelly'}]
I would want to add a new field called first_word:
alist =[{'id':1, 'text':'Dogs are great', 'first_word':'Dogs'},
{'id':2, 'text':'Cats are great', 'first_word':'Cats'},
'id':3, 'text':'Fish are smelly', 'first_word':'Fish'}]
The code which I have use to attempt this is below:
for ditem in alist:
ditem['first_word'] = ditem['text'].split()[0]
however I am receiving the error:
IndexError: list index out of range
How can I do this?
Ad
Answer
There are probably dicts in your list whose 'text' is empty.
You can either sanitize your data or, if you want to ignore the empty texts and add an empty 'first_word' in this case, you could do:
for ditem in alist:
ditem['first_word'] = ditem['text'].split()[0] if ditem['text'] else ''
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad