Cannot append string to dictionary key

24,663

Solution 1

You can't .append() to a string because a string is not mutable. If you want your dictionary value to be able to contain multiple items, it should be a container type such as a list. The easiest way to do this is just to add the single item as a list in the first place.

if clientKey not in data:
    data[clientKey] = [ref]   # single-item list

Now you can data[clientkey].append() all day long.

A simpler approach for this problem is to use collections.defaultdict. This automatically creates the item when it's not there, making your code much simpler.

from collections import defaultdict

data = defaultdict(list)

# ... same as before up to your if

if clientkey in data and ref in data[clientkey]:
    print("That invoice already exists")
else:
    data[clientKey].append(ref)

Solution 2

You started with a string value, and you cannot call .append() on a string. Start with a list value instead:

if clientKey not in data:
    data[clientKey] = [ref]

Now data[clientKey] references a list object with one string in it. List objects do have an append() method.

Solution 3

If you want to keep appending to the string you can use data[clientKey]+= ref

Share:
24,663
Shahram
Author by

Shahram

Updated on November 19, 2020

Comments

  • Shahram
    Shahram over 3 years

    I've been programming for less than four weeks and have run into a problem that I cannot figure out. I'm trying to append a string value to an existing key with an existing string stored in it but if any value already exists in the key I get "str object has no attribute 'append'.

    I've tried turning the value to list but this also does not work. I need to use the .append() attribute because update simply replaces the value in clientKey instead of appending to whatever value is already stored. After doing some more research, I understand now that I need to somehow split the value stored in clientKey.

    Any help would be greatly appreciated.

    data = {}
    
    while True:
    
        clientKey = input().upper()
        refDate = strftime("%Y%m%d%H%M%S", gmtime())
        refDate = refDate[2 : ]
        ref = clientKey + refDate
    
        if clientKey not in data:
            data[clientKey] = ref
    
        elif ref in data[clientKey]:
            print("That invoice already exists")
    
        else:
            data[clientKey].append(ref)
    
            break