如何在Python中将元素追加到字典中的列表

时间:2019-11-01 14:26:11

标签: python list dictionary

我查看了以下帖子:append list inside dictionary with updateAppend element to smallest list in dictionary of lists。 他们没有帮助我。我想做这样的事情:有一个result = {}spl = input().split(' '),我做了 something ,然后变成了result = {'text': [1, 2]}(例如)。该怎么做?

我尝试做出第一个链接中的内容:result.update({'text': result['text'] + [1, 2]}),但是没有用。我还尝试了第二个链接中的内容:

result = {'text': []}
result['text'].append(1, 2)

但是它给了我一个错误AttributeError: 'str' object has no attribute 'append'。真正的代码部分,直到所需的部分都在下面。

代码:

def checkThru(txt, wordsDesc=1, countMoreMost=False, indexInOutput=False):
    result = {}
    spl = txt.split(' ')
    badChars = ['?', ',', '.', '!',]
    wordam = list(range(0, wordsDesc))

    for lol in range(len(spl)):
        for sublol in badChars:
             spl[lol] = spl[lol].replace(sublol, "")

    for i in spl:

        iinspl = spl.index(i)

        if indexInOutput == True:

            if i == 'are' or i == 'am' or i == 'is' or i == 'were' or i == \
            'was' or i == 'will' or i == 'shall':

                if spl[iinspl + 1] == 'a' or spl[iinspl + 1] == 'an' or \
                spl[iinspl + 1] == 'the':

                    if countMoreMost == False:

                        if spl[iinspl + 2] == 'more' or spl[iinspl + 2] == 'most':

                            result.update({iinspl-1: []})

                            for add in wordam:

                                result.update({spl[iinspl-1].append(iinspl+3+add)}) #???(Here's where the error says something is wrong.)
#Actually, spl[iinspl-1] is going to be a list, because of the line <<result.update({iinspl-1: []})>>

跟踪:

Traceback (most recent call last):
  File "D:\python\I MADE A MODULE!!! indeX.py", line 16, in <module>
    print(indeX.checkThru('Hello, I am David. My sister is the most Ann babe', 1, False, True))
  File "C:\Users\Danil\AppData\Local\Programs\Python\Python37-32\lib\indeX.py", line 287, in checkThru
    result.update({spl[iinspl-1].append(iinspl+1+add)})
AttributeError: 'str' object has no attribute 'append'

我希望它制作一个特征字典。例如:

print(checkThru('Hi, I am David, and my sister is Ann!'))

>>> {'I': ['David'], 'sister': ['Ann']}

3 个答案:

答案 0 :(得分:2)

您的代码:

result = {'text': []}
result['text'].append(1, 2)

除非您在尝试追加之前将AttributeError: 'str' object has no attribute 'append'的值定义为字符串,否则不要给出result['text']

但是,append不需要两个这样的参数。如果要将12添加到列表中,请执行以下操作之一:

result = {'text': []}
result['text'].append(1)
result['text'].append(2)

print(result)

打印:

{'text': [1, 2]}

result = {'text': []}
result['text'] += [1, 2]

print(result)

打印:

{'text': [1, 2]}

答案 1 :(得分:0)

result = {'text': []} result['text'].append(1, 2)

会给予

  

TypeError:append()仅接受一个参数(给定2个)   因为append只接受一个参数。不是您提到的那个。

一种方法是,如果您不想返回列表列表,则逐个元素追加。 result = {'text':[]} result['text'].append(1) result['text'].append(2) result {'text': [1, 2]}将提供理想的结果

或改用update。语法似乎很好:

result.update({'text': [1, 2]}) result {'text': [1, 2]}

话虽如此, 快速查看代码后:

  1. 所有决定都是通过if条件(仅是if-nested块)触发的,因此应该True进行所有修改,以使result字典得到修改,请复查一次。
  2. 该函数的默认参数以False开头,因此检查代码是否与True相对,因此该程序在第一次检查后不会退出。

{注意:尝试运行一段代码会打印语句,可以帮助您正确理解逻辑}

答案 2 :(得分:-1)

您发布的第二个链接:

result = {'text': []}
result['text'].append(1, 2)

...将起作用。您收到的错误是因为它说的是-您正在尝试对字符串运行append。

您的spl列表是由txt.split()产生的字符串列表。您的代码:

spl[iinspl-1].append()

...因此将始终尝试追加到一个字符串,而该字符串(如您所发现的)无效。

我认为可能在那段代码中,您是要附加到result而不是spl上?

编辑:否则,您需要类似的东西:

result[spl[iinspl-1]].append(iinspl+3+add))

可能要更新而不是追加,具体取决于其中的内容和所需的内容。