Ad

How Do You Split A Dictionary String Value In A List Of Dictionaries To Add A New Dictionary Item?

- 1 answer

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
Ad