简体   繁体   English

如何在字典列表中拆分字典字符串值以添加新的字典项?

[英]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. 我有一个字典列表,每个列表中都有一个名为text的键,其中包含字符串值。 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. 对于每个字典,我想添加一个名为first_word的新项,它是文本字符串的一个分区,用于获取代码。

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: 我想添加一个名为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 IndexError:列表索引超出范围

How can I do this? 我怎样才能做到这一点?

Pass an empty space character to the split method, like : 将空格字符传递给split方法,如:

for ditem in alist:
    ditem['first_word'] = ditem['text'].split(' ', 1)[0]

Use the second argument to .split() to let the splitting stop early in case your strings are big. 使用.split()的第二个参数让分裂停止,以防你的字符串很大。

Your code works well apart from the typo. 除了拼写错误之外,您的代码运行良好。 You missed a { before the third item. 你错过了{在第三项之前。

Jupyter throws this Jupyter抛出这个

  File "<ipython-input-17-6aeaa3a052d5>", line 5
    'id':3, 'text':'Fish are smelly'}]
        ^
SyntaxError: invalid syntax

Just amend it 只是修改它

alist =[{'id':1, 'text':'Dogs are great'},
{'id':2, 'text':'Cats are great'},
{'id':3, 'text':'Fish are smelly'}]

for ditem in alist:
    ditem['firstword']=ditem['text'].split()[0]

alist

Output: 输出:

[{'id': 1, 'text': 'Dogs are great', 'firstword': 'Dogs'},
 {'id': 2, 'text': 'Cats are great', 'firstword': 'Cats'},
 {'id': 3, 'text': 'Fish are smelly', 'firstword': 'Fish'}]

You have an error in your dictionary. 您的词典中有错误。 Look at line 3 if a list you're missing a curly brace. 如果列表中缺少大括号,请查看第3行。

alist =[{'id':1, 'text':'Dogs are great'}, {'id':2, 'text':'Cats are great'}, {'id':3, 'text':'Fish are smelly'}]

def append_kv(dd):
    dd['first_word '] = ''
    return dd

alist = [append_kv(dd) for dd in alist]

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: 您可以清理数据,或者,如果您想忽略空文本并在这种情况下添加空的'first_word',您可以执行以下操作:

for ditem in alist:
    ditem['first_word'] = ditem['text'].split()[0] if ditem['text'] else ''

The particular IndexError you mentioned should only happen when you try to access a list element that doesn't exist. 您提到的特定IndexError只应在您尝试访问不存在的列表元素时发生。 You have exactly one list access (the list output from ditem['text'].split() , and you're trying to access it's first element, so that list must be empty. This happens precisely when ditem['text'] is empty, which gives us a quick fix: check to see if it's empty. 您只有一个列表访问权限(来自ditem['text'].split()的列表输出ditem['text'].split() ,并且您正在尝试访问它的第一个元素,因此该列表必须为空。这恰好在ditem['text']是空的,这给了我们一个快速修复:检查它是否为空。

for ditem in alist:
    t = ditem['text']
    ditem['first_word'] = t.split()[0] if t else None

Putting aside the missing brace, your code works on the input you show. 抛开缺少的括号,您的代码将对您显示的输入起作用。

The only circumstances in which you'd get a list index out of range exception is if text is empty: 您获得list index out of range异常的唯一情况是text是否为空:

In [11]: for ditem in alist:
    ...:     ditem['first_word'] = ditem['text'].split()[0]
    ...:
IndexError: list index out of range

One way to fix this is by explicitly handling empty text: 解决此问题的一种方法是显式处理空文本:

In [12]: for ditem in alist:
    ...:     ditem['first_word'] = ditem['text'].split()[0] if ditem['text'] else ''
    ...:
    ...:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将列表作为新项目加入列表字典-python? - How do you join a list to a dictionary of lists as a new item - python? Python:如何遍历词典列表并将每个词典作为值添加到具有唯一键的新词典中-无需重复 - Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats 将字典拆分成词典列表 - Split a dictionary into a list of dictionaries 如何在新窗口中显示词典列表中每本词典的最后一项? - How to display in a new window the last item of each dictionary in a list of dictionaries? 为字典列表中的每个项目分配字典值 - Assign dictionary value for every item in list of dictionaries 如何从字典列表中删除字典? - How do you delete a dictionary from a list of dictionaries? 如何根据用户指定的值从字典列表中的字典中删除键? - How do you delete a key from a dictionary within a list of dictionaries based on a user specified value? 将字典添加到词典列表 - Add a dictionary to list of dictionaries 如果与列表中每个字典中的一个键的值匹配,则将具有不同词典值的新键添加到词典列表中 - Add new key to list of dictionaries with the values from a different dictionaries if matched with value of one key in each dictionary in a list 将列表字典拆分为字典列表 - Split dictionary of lists into list of dictionaries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM