Skip to content Skip to sidebar Skip to footer

How I Can Fix This Error? TypeError: List Indices Must Be Integers Or Slices, Not Str

I have a list like this: mylist[1:3]=[{'Keywords': 'scrum master', 'result': {'categoryId': '3193', 'categoryName': 'agile coach', 'score': '1.0'}, 'categoryId': '3193'},

Solution 1:

You have to define mylist at the beginning, and add an if test for its elements, then the code works:

mylist = []
mylist[1:3]=[{'Keywords': 'scrum master',
              'result': {'categoryId': '3193',
                         'categoryName': 'agile coach',
                         'score': '1.0'},
              'categoryId': '3193'},
             {'Keywords': 'principal consultant',
              'result': {'categoryId': '2655',
                         'categoryName': 'principal consultant',
                         'score': '1.045369052886963'},
              'categoryId': '2655'},
             {'Keywords': 'technicalfunctional consultant',
              'result': []}]
categories = set(x['result']['categoryName'] for x in mylist
                 if x['result'] and 'categoryName' in x['result'])
print(categories)
# {'agile coach', 'principal consultant'}

Regarding the question in the comment below: to make that code work, define the variables before using them, and add another if condition:

cat_dict = {}
cat_set = set(['agile coach', 'principal consultant'])

for cat_name in cat_set:
    cat_dict[cat_name] = [elem["Keywords"] for elem in mylist
                          if elem["result"] and elem["result"]["categoryName"] == cat_name] 
    
print(cat_dict)
# {'agile coach': ['scrum master'], 'principal consultant': ['principal consultant']}

Post a Comment for "How I Can Fix This Error? TypeError: List Indices Must Be Integers Or Slices, Not Str"