简体   繁体   English

如何 append 列出 Python 中字典中的元素

[英]How to append an element to list that is in dictionary in Python

I reviewed those posts: append list inside dictionary with update and Append element to smallest list in dictionary of lists .我查看了这些帖子: append list inside dictionary with updateAppend element to minimum list in dictionary of lists They didn't help help me.他们没有帮助我。 I wanted to do something like that: there was a result = {} and spl = input().split(' ') , I did something and it turned into result = {'text': [1, 2]} (for example).我想做这样的事情:有一个result = {}spl = input().split(' ') ,我做了一些事情,结果变成了result = {'text': [1, 2]} (对于例子)。 How to do this?这个怎么做?

I tried to make a thing like in the first link: result.update({'text': result['text'] + [1, 2]}) , but it did not worked.我试图在第一个链接中做类似的事情: result.update({'text': result['text'] + [1, 2]}) ,但它没有奏效。 I also tried thing from the second link:我还尝试了第二个链接的事情:

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

but it gave me an error AttributeError: 'str' object has no attribute 'append' .但它给了我一个错误AttributeError: 'str' object has no attribute 'append' The real code part until the intended part is down below.真正的代码部分,直到预期的部分在下面。

The code:编码:

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:追溯:

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'

I wanted it to make a dictionary of characteristics.我想让它制作一本特征字典。 For example:例如:

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

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

Your code:你的代码:

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

Shouldn't give AttributeError: 'str' object has no attribute 'append' unless you define the value of result['text'] as a string before trying to append.不应给出AttributeError: 'str' object has no attribute 'append'除非您在尝试 append 之前将result['text']的值定义为字符串。

However, append doesn't take two arguments like that.但是, append不会像这样占用两个 arguments。 If you want to add 1 and 2 to the list, you would do one of:如果要将12添加到列表中,可以执行以下操作之一:

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

print(result)

prints:印刷:

{'text': [1, 2]}

or或者

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

print(result)

prints:印刷:

{'text': [1, 2]}

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

Will give会给

TypeError: append() takes exactly one argument (2 given) because append takes only one argument. TypeError: append() 只接受一个参数(给定 2 个),因为 append 只接受一个参数。 Not the one you have mentioned.不是你提到的那个。

One way to go is append element by element if you dont want to return a list of list.如果您不想返回列表列表,则 go 的一种方法是 append 元素一个元素。 result = {'text':[]} result['text'].append(1) result['text'].append(2) result {'text': [1, 2]} will give the desired result result = {'text':[]} result['text'].append(1) result['text'].append(2) result {'text': [1, 2]}会给出想要的结果

Or use update instead.或者改用update The syntax seems fine:语法看起来不错:

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

Having said that, After a quick review of the code:话虽如此,在快速查看代码之后:

  1. All the decisions are triggered via if conditions (only if-nested blocks) so all should be True such that your result dictionary gets modified please review that once.所有决定都是通过 if 条件(仅 if 嵌套块)触发的,因此所有决定都应该是True以便您的result字典被修改,请检查一次。
  2. Default parameters to the function start with False the check the code does is against True hence it will not the program will exit after first check itself. function 的默认参数以False开头,代码所做的检查是针对True的,因此它不会在第一次检查自身后退出程序。

{Note: A dry run of the code will print statements can help you get the logic right} {注意:代码的空运行将打印语句可以帮助您获得正确的逻辑}

The second-link thing you posted:您发布的第二个链接内容:

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

...will work. ...将工作。 The error you're getting is because of what it says - you're trying to run append on a string.你得到的错误是因为它说的 - 你试图在一个字符串上运行 append 。

Your spl list is a list of strings, resulting from txt.split() .您的spl列表是一个字符串列表,由txt.split()产生。 Your code:你的代码:

spl[iinspl-1].append()

...will therefore always be trying to append to a string, which (as you're finding) doesn't work. ...因此将始终尝试将 append 转换为字符串,这(正如您所发现的)不起作用。

I think probably in that bit of code you mean to be appending to result , not spl ?我想可能在你的意思是附加到result的那段代码中,而不是spl

EDIT: Or else you want something like:编辑:或者你想要类似的东西:

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

Might be update rather than append, depending on exactly what's in there and what you want out.可能是更新而不是 append,具体取决于那里的内容和您想要的内容。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM