Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Azadeh Oveisi
The Python "TypeError: list indices must be integers or slices, not dict"
occurs when we use a dictionary to access a list at a specific index. To solve
the error, use an integer or a slice for list indexes, e.g. my_list[0]
.
Here is an example of how the error occurs.
my_dict = {'name': 'Alice', 'age': 30} my_list = ['a', 'b', 'c'] # ⛔️ TypeError: list indices must be integers or slices, not dict result = my_list[my_dict]
The error is caused because we are using a dictionary as a list index.
my_list[2]
) or a slice (e.g. my_list[0:2]
) for list indices.If you are iterating over a list of dictionaries, make sure to access key-value pairs of the dictionary on each iteration.
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] for entry in my_list: print(entry['id']) print(entry['name'])
We used a for
loop to iterate over a list of dictionaries.
entry
variable stores a dictionary on each iteration, so you can access it at a specific key to get the corresponding value.You can use an index to access a specific dictionary in the list and then access the specific key of the dictionary.
my_list = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] result = my_list[0]['name'] print(result) # 👉️ 'Alice'
If you have a dictionary with a list value, access the specific key before accessing an index.
my_dict = { 'fruits': ['apple', 'banana', 'kiwi'] } result = my_dict['fruits'][0] print(result) # 👉️ 'apple'
If you need to iterate over a dictionary, use the dict.items()
method.
my_dict = {'name': 'Alice', 'age': 30} for key, value in my_dict.items(): print(key, value) # 👉️ name Alice, age 30
The dict.items method returns a new view of the dictionary's items ((key, value) pairs).
If you need to get a slice of a list, use a colon to separate the start and end indices.
my_list = ['a', 'b', 'c', 'd', 'e'] print(my_list[0:3]) # 👉️ ['a', 'b', 'c'] print(my_list[3:]) # 👉️ ['d', 'e']
The start index is inclusive, whereas the end index is exclusive (up to, but not including).
If you aren't sure what type of object a variable stores, use the type()
class.
my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # 👉️ <class 'dict'> print(isinstance(my_dict, dict)) # 👉️ True my_list = ['a', 'b', 'c'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.