首页 > 解决方案 > 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'},
 {'Keywords': 'principal consultant',
  'result': {'categoryId': '2655',
   'categoryName': 'principal consultant',
   'score': '1.045369052886963'},
  'categoryId': '2655'}, 
 {'Keywords': 'technicalfunctional consultant',
  'result': []}]

I want to run the following code:

categories=set(x['result']['categoryName'] for x in mylist)

It gives me the error:

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

标签: pythonlistdictionaryset

解决方案


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']}

推荐阅读