TypeError: list indices must be integers or slices, not str

PythonArraysListCsv

Python Problem Overview


I've got two lists that I want to merge into a single array and finally put it in a csv file. I'm a newbie with Python arrays and I don't understand how I can avoid this error :

def fill_csv(self, array_urls, array_dates, csv_file_path):
    result_array = []
    array_length = str(len(array_dates))

    # We fill the CSV file
    file = open(csv_file_path, "w")
    csv_file = csv.writer(file, delimiter=';', lineterminator='\n')

    # We merge the two arrays in one

    for i in array_length:
        result_array[i][0].append(array_urls[i])
        result_array[i][1].append(array_dates[i])
        i += 1

    csv_file.writerows(result_array)

And got :

  File "C:\Users\--\gcscan.py", line 63, in fill_csv
    result_array[i][0].append(array_urls[i])
TypeError: list indices must be integers or slices, not str

How can my count work ?

Python Solutions


Solution 1 - Python

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

Solution 2 - Python

Follow up on Abdeali Chandanwala answer above (couldn't comment because rep<50) -

TL;DR: I was trying to iterate through a list of dictionaries incorrectly by focusing to iterate over the keys in the dictionary but instead had to iterate over the dictionaries themselves!


I came across the same error while having a structure like this:

{
   "Data":[
      {
         "RoomCode":"10",
         "Name":"Rohit",
         "Email":"[email protected]"
      },
      {
         "RoomCode":"20"
         "Name":"Karan",
         "Email":"[email protected]"
      }
   ]
}

And I was trying to append the names in a list like this-

Same error received

Fixed it by-

Fixed the error

Solution 3 - Python

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and I had to made sure that I only add dictionary objects to that list and list typed object into the list, this solved my issue as well.

Solution 4 - Python

In my case I was trying to change the value of a dict key but since my dict was there in a for loop and was getting changed to type list i was getting the same error.

for value in source_list:
    my_dict['my_key']=some_val
    dict=list(mydict)
    exctraction0 = dict[0]

i resolved it by making sure the type of dict remains the same by making a deepcopy and re-initializing after every iteration(that is what the use-case was all about).

copy_dict = copy.deepcopy(my_dict)
for value in source_list:
    my_dict =copy.deepcopy(copy_dict)
    my_dict['my_key']=some_val
    dict=list(mydict)
    exctraction0 = dict[0]

Solution 5 - Python

I received this error overloading a function in python where one function wrapped another:

def getsomething(build_datastruct_inputs : list[str]) -> int:
      # builds datastruct and calls getsomething
      return getsomething(buildit(build_datastruct_inputs))

def getsomething(datastruct : list[int]) -> int:
      # code
      # received this error on first use of 'datastruct'

Fix was to not overload and use unique method name.

def getsomething_build(build_datastruct_inputs : list[str]) -> int:
      # builds datastruct and calls getsomething
      return getsomething_ds(buildit(build_datastruct_inputs))

def getsomething_ds(datastruct : list[int]) -> int:
      # code
      # works fine again regardless of whether invoked directly/indirectly

Another fix could be to use python multipledispatch package which will let you overload and figures this out for you.

Was a bit confusing because where the error was occuring (nor message) corresponded to what cause was. I thought I had seen that python supported overloading natively but now I've learned it's implementation requires more work from the user.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArthur C-GView Question on Stackoverflow
Solution 1 - PythonAlexanderView Answer on Stackoverflow
Solution 2 - PythonrohetoricView Answer on Stackoverflow
Solution 3 - PythonAbdeali ChandanwalaView Answer on Stackoverflow
Solution 4 - PythonofficialrahulmandalView Answer on Stackoverflow
Solution 5 - PythonjoshView Answer on Stackoverflow