Sunday, 5 April 2020

list indices must be integers or slices, not str error in python

Below is an example to elaborate the error and for an better understanding.

Eg:

shops = [{
    "name""Anand Motors",
    "cars": [
        {
            "name":"Ferrari",
            "Price"25000
        },
        {
            "name""Benz",
            "price"15000
        }
    ]}  
]

The above dictionary is referred as list, when to try to access the dictionary data using string.

name = "Anand Motors"
print(shops[name])

The above code gives error.

Solution or fix:

name = "Anand Motors"
print(next(shop for shop in shops if shop["name"== name))

The above code will fix this error.


No comments:

Post a Comment

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...