String Indices Must Be Integers in Python

String Indices Must Be Integers in Python

  1. Access the Nested Key Without Error From JSON Data in Python
  2. Slice the List Without Error in Python

We will learn, with this explanation, how to access nested keys from JSON data and see why beginners fail to access a nested key. We will also learn how to slice a list without error in Python.

Access the Nested Key Without Error From JSON Data in Python

We will look at how we can access information from nested dictionaries, and for demonstration, we will create JSON data. First, we must import the json module to convert JSON data into Python object format because Python, by default, cannot work with JSON data.

import json
EMP_DATA = '{"tech_companies":{"company":"Google","Country":"US"},"Employee":[{"Name":"Alex","emp_id":108,"Age":25}],"Microsoft":{"emp_name":"sarah","emp_age":29}}'
JSON_DATA = json.loads(EMP_DATA)

Now, we will access the nested key of Employee that holds a list as a value, and we need to access the Name key that is part of a list item. Since the Employee key has a value, and that value is a list, we can also iterate it using its value.

for i in JSON_DATA['Employee']:
    print(i['Name'])

Output:

Alex

Let’s say we want to use the Microsoft key to access its value. The value is a nested dictionary; hence, we will access the first key in this case.

for j in JSON_DATA['Microsoft']:
    print(j['emp_name'])

Output:

TypeError: string indices must be integers

When we run the code, we would get an error because the j variable contains a key string, and we are trying to access the emp_name value.

In that case, the j variable contains emp_name, which is a string, and when the control reads j['emp_name'], the interpreter control tries to recognize string indices, but it fails because Python accepts an integer, but we passed string. Most beginners make this type of mistake when accessing nested data.

It depends on what the user wants to operate; in our case, we are trying to access a particular key’s value.

To access the nested dictionary key, we will use the following code:

for j in JSON_DATA['Microsoft']:
    print(JSON_DATA['Microsoft']['emp_name'])

Output:

sarah
sarah

Complete Python Code:

import json
EMP_DATA = '{"tech_companies":{"company":"Google","Country":"US"},"Employee":[{"Name":"Alex","emp_id":108,"Age":25}],"Microsoft":{"emp_name":"sarah","emp_age":29}}'
JSON_DATA = json.loads(EMP_DATA)
for i in JSON_DATA['Employee']:
    print(i['Name'])

for j in JSON_DATA['Microsoft']:
    print(JSON_DATA['Microsoft']['emp_name'])
    print(type(j))
    print(j)

Slice the List Without Error in Python

We will discuss the same error in another scenario (list indices must be integers or slices). Let’s now jump into the code to see how we can fix this.

If you manually generate or create it and do not format the list correctly, you will get the same error we discussed.

z=[[2,3,5,6][1,2,3,10]]
print(z[0])

Output:

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

The reason for getting this error is during the code execution; when the control reads the z variable, it recognizes that the z variable stores two lists but does not find a separator. To fix this error, we must put the missing comma between two lists to separate them.

z=[[2,3,5,6],[1,2,3,10]]
print(z[0])

Output:

[2, 3, 5, 6]

In the other scenario, we will show you that sometimes beginners try to access some list items but often make a mistake, which is why they get the same error.

fruits=['Apple','Banana','Orange','Mango']
print(fruits[0:,2])

Output:

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

This error occurs because we are trying to slice a list that returns a list with two items, but the slice needs an integer after the colon, not a comma or string. If you make these types of mistakes, then you must clear the basic programming concept.

fruits=['Apple','Banana','Orange','Mango']
print(fruits[0:2])

Output:

['Apple', 'Banana']
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10