Aditya Singh Aditya Singh - 6 months ago 26
Python Question

string index out of range django

I am trying to iterate for an array but it throws the above error

here is the view:

brand_category = self.request.POST.get('parameter[]')
for D in brand_category:
print brand_category
brands, categories = D[0] , D[1]
print brands , categories


brand_category
looks like this:

{"spykar":["Jeans","Sweater"],"Madame":["Tops","jeans"]}


here is the traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\sellers\views.py" in post
329. brands, categories = D[0] , D[1]

Answer

First of all, brand_category is not an array but a dictionary. If you do for D in brand_category, you were just looping through the keys. To loop the dictionary properly, do:

for brand, categories in brand_category.iteritems():
    print brand, categories

If you want to loop on the values which are lists, do:

for brand, categories in brand_category.iteritems():
    print brand
    for category in categories:
        print category
Comments