How to append an element to list that is in dictionary in Python

python dictionary
python add to dictionary in loop
append dictionary python
python dictionary add key-value pair
convert list to dictionary python
python dictionary value list append
python add multiple items to dictionary
python dictionary add value to existing key

I reviewed those posts: append list inside dictionary with update and Append element to smallest 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). 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. 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'. 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']}

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.

Your spl list is a list of strings, resulting from 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.

I think probably in that bit of code you mean to be appending to result, not 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.

Appending to list in Python dictionary, value of existing keys. Python dictionary provides a member function update() i.e. Adding a list of tuples (key value pairs) in dictionary. # Adding a List of tuples to Adding elements from dict2 to dict1. dict1.update( dict2 ). I want to add an item to an existing dictionary in Python. For example, this is my dictionary: default_data = { 'item1': 1, 'item2': 2, } I want to add a new item such tha

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.

However, append doesn't take two arguments like that. If you want to add 1 and 2 to the list, you would do one of:

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]}

Python : How to add / append key value pairs in dictionary using dict , Iterate the list and keep appending the elements till given range using setdefault () method. filter_none. edit close. play_arrow. link brightness_4 code� To perform adding new items, you have to use the update () function of Python. The function takes Dictionary item as the argument to pass which you want to append. The element appends to the end of the Dictionary using Python. You can append only single element or items in Dictionary using this method.

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

Will give

TypeError: append() takes exactly one argument (2 given) because append takes only one argument. 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. result = {'text':[]} result['text'].append(1) result['text'].append(2) result {'text': [1, 2]} will give the desired result

Or use update instead. 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.
  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.

{Note: A dry run of the code will print statements can help you get the logic right}

Python, Recall, how in lists and strings, we used the index as the parameter to access each element of the string/list. The main differentiating factor between a list and a � How to Add to Dictionary in Python. 1. By Using update() Method; 2. By Using _setitem_() Method; 3. By Using Subscript Notation; 4. By Using ” ** ” Operator; Adding Keys to Nested Python Dictionary; Addition of Multiple Key-Value Pairs to Python Dictionary; Addition of a Dictionary to Another Dictionary; Conclusion; References

Python Dictionaries, Also, the last item is considered to be at position -1. The most common operation is to add a new element to the end of the list with the .append()� In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them. Create a List of Dictionaries in Python In the following program, we create a list of length 3, where all the three elements are of type dict.

Manipulating Lists and Dictionaries in Python, Now I want to append 'twofour' to the list of the 'two' key but I can't figure out how to that? Some pointers would be greatly appreciated. Thanks Append multiple key value pair in dictionary As update () accepts an iterable sequence of key value pairs, so we can pass a dictionary or list of tuples of new key value pairs to update (). It will all add the given key value pairs in the dictionary, if any key already exists then it will update its value.

Append data to a list within a dict - Python, Add an item to the end of the list. It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys� list.append(item) It adds the item at the end of list. For example, we have a list of string i.e. # List of string wordList = ['hi', 'hello', 'this', 'that', 'is', 'of'] Now let’s add an element at the end of this list using append() i.e. ''' Adding item in list using list.append() ''' wordList.append("from") Now list will become,

Comments
  • It would be nice if you could make your question smaller. And please add the traceback. Which lines causes the AttributeError?
  • Running your code: result['text'].append(1, 2) gives me TypeError: append() takes exactly one argument (2 given), not the AttributeError you posted.
  • .append(1, 2) was just an example
  • Accurate examples will help a lot more with answering your question
  • When I use result[spl[iinspl-1]].update({iinspl-1: [iinspl+1+add]}) with print(indeX.checkThru('Hello, I am David. My sister is the most Ann babe', 1, False, True)) it outputs: KeyError: 'I', because spl[iinspl-1] = 'I' but I will try earlier thing you said.
  • I tried to do this: result.update({spl[iinspl-1]: [iinspl+2+add]}) but it didn't worked((( For some reason it outputs: TypeError: 'int' object is not iterable
  • When I do this: result[iinspl-1] += spl(iinspl+1+add), it outputs: TypeError: 'list' object is not callable
  • it looks like spl is a list based on the error. So you can't call it like spl(args).