-2

I am using a dictionary to add key and values in it. I am checking if the key is already present, and if yes, I am appending the value; if not I add a key and the corresponding value.

I am getting the error message:

AttributeError: 'str' object has no attribute 'append'

Here is the code. I am reading a CSV file:

metastore_dir = collections.defaultdict(list)
with open(local_registry_file_path + data_ext_dt + "_metastore_metadata.csv",'rb') as metastore_metadata:
    for line in metastore_metadata: 
        key = line[2]
        key = key.lower().strip()
        if (key in metastore_dir):
            metastore_dir[key].append(line[0])
        else:
            metastore_dir[key] = line[0]

I found the answer on stack overflow which says to use defaultdict to resolve the issue, i am getting the error message even after the suggested anwer. I have pasted my code for reference.

3 Answers3

0

The str type has no append() method. Replace your call to append with the + operator:

sentry_dir[key] += line[1]
Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24
0

It is a dictionary of strings. To declare it as a list use

    if (key not in metastore_dir):  ## add key first if not in dict
        metastore_dir[key] = []  ## empty list
    metastore_dir[key].append(line[0])

    """ with defaultdict you don't have to add the key
        i.e. "if key in" not necessary
    """
    metastore_dir[key].append(line[0])
0

When you insert a new item into the dictionary, you want to insert it as a list:

...
if (key in metastore_dir):
    metastore_dir[key].append(line[0])
else:
    metastore_dir[key] = [line[0]] # wrapping it in brackets creates a singleton list

On an unrelated note, it looks like you are not correctly parsing the CSV. Trying splitting each line by commas (e.g. line.split(',')[2] refers to the third column of a CSV file). Otherwise line[0] refers to the first character of the line and line[2] refers to the third character of the line, which I suspect is not what you want.

Flight Odyssey
  • 2,267
  • 18
  • 25