TypeError: list indices must be integers or slices, not str
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)
TypeError: list indices must be integers or slices, not str - While accessing element of list
I was solve this by the following
Passing
[{"id":9,"name":"Foo"}]
instead of['{"id":9,"name":"Foo"}']
which can done by removingjson_encode()
while sending data to Flask Application. In my case was from Laravel / PHP.By accessing element using
a[0]['id']
as pointed by @mhhabib
How to fix TypeError: list indices must be integers or slices, not str. ?
There are two main issues:
You are not iterating the
ResultSet
of urls, you pushtable
as list of urls to your function.Your urls become invalid, while prepending
baseUrl
, just try to usejobUrl = link['href']
cause path is absolute.
Note You also should check if the elements you are looking for exists in the responses
Example
Iterates over the first two urls - Third will give you an error, cause there is no <h3>
in response, but this should be asked in new question with exact this focus:
def jobScan(link):
the_job = {}
jobUrl = link['href']
print(jobUrl)
the_job['urlLink'] = jobUrl
job = requests.get(jobUrl, headers = headers )
jobC = job.content
jobSoup = BeautifulSoup(jobC, "lxml")
name = jobSoup.find("h3", attrs={"class": "loop-item-title"})
title = name.a.text
the_job['title'] = title
company = jobSoup.find_all("span", {"class": "job-company"})[0]
company = company.text
the_job['company'] = company
return the_job
data = []
for a in table[:2]:
data.append(jobScan(a))
data
Output
[{'urlLink': 'https://elitejobstoday.com/jobs/office-assistant-ngo-careers-at-world-vision-uganda/',
'title': 'Project Accountant – Lego Foundation Playful Parenting Project (NGO Careers) at World Vision Uganda',
'company': ' World Vision Uganda\n'},
{'urlLink': 'https://elitejobstoday.com/jobs/survey-enumerators-41-positions-ngo-careers-at-catholic-relief-services-2022/',
'title': 'Project Accountant – Lego Foundation Playful Parenting Project (NGO Careers) at World Vision Uganda',
'company': ' Catholic Relief Services (CRS)\n'}]
Finding a needle in a haystack *TypeError: list indices must be integers or slices, not str*
There are different numbers involved here - you have the value/element (i.e. the thing you're adding to the array) and the index; the element's position within that array. When comparing your needle value with your haystack value you want to compare the values (which you're doing); but to get those values you want to look in the array in the relevant position (which you're not).
Instead, try something like this:
needle = []
for x in range(2015,2017):
needle.append(str(x))
hay = []
for x in range(2015,2022):
hay.append(str(x))
print(needle)
print(hay)
for needleIndex in range(len(needle)):
for hayIndex in range(len(hay)):
if needle[needleIndex] == hay[hayIndex]:
print("Found!")
else:
print("Not found!")
This change means that instead of a
being '2015'
, '2016'
, '2017'
instead needleIndex
is 0
,1
,2
and needle[needleIndex]
is '2015'
, '2016'
, '2017'
.
Hope that helps to clarify what's going on.
ps. For this example you don't need the indexes; you could just have
for a in needle:
for b in hay:
if b == a:
print("Found!")
else:
print("Not found!")
Simpler still; you've shown that you're aware of the in
operator; though you've been comparing individual values from the 2 arrays (hence I changed it to ==
above)... You can use your in
operator like this:
for a in needle:
if a in hay:
print("Found!")
else:
print("Not found!")
You can also use the array_intersect
function to check for all elements which exist in both arrays... More on that here: https://stackoverflow.com/a/8679430/361842
Related Topics
How to Use Win32 API with Python
Cancel an Already Executing Task with Celery
Why Does Pyplot.Contour() Require Z to Be a 2D Array
Importerror When Importing Tkinter in Python
Executing Command Line Programs from Within Python
<Django Object > Is Not JSON Serializable
How to Represent an Infinite Number in Python
What Is the Most Compatible Way to Install Python Modules on a MAC
Unicodeencodeerror: 'Latin-1' Codec Can't Encode Character
Python Unittest.Testcase Execution Order
Python SQLite Parameter Substitution with Wildcards in Like
Except-Clause Deletes Local Variable
Memory-Efficient Built-In SQLalchemy Iterator/Generator
Schedule a Repeating Event in Python 3
Why Doesn't Exec Work in a Function with a Subfunction
How to Timeout Function in Python, Timeout Less Than a Second