字符串索引必须是整数,而不是字典中的str

时间:2014-11-21 08:45:42

标签: python dictionary

我使用代码创建这样的嵌套字典: 词典:

{u'Titanic': {'match': [{'category': u'Book'},
                        {'category': u'Movie'},
                        {'category': u'Product'}],
              'score': 100}}

泰坦尼克号是实体,book, movie, product是类。分数无需考虑。

        grams_to_check_dict = {}
        grams_to_check_dict['key'] = {}
        #grams_to_check_dict['key']['matches'] = []
        print 'No entities detected'
        print "-"*40
        while(True):
            print '\tDo you want to add Entity Y/N ?'
            print '\t'
            choice = raw_input()
            if choice == 'N' or choice == 'n':
                break
            elif choice == 'Y' or choice == 'y' :
                print '\tEnter Entity : \t'
                Entity =  raw_input()
                #grams_to_check_dict['key'] = Entity
                print '\tHow many class do you want to add for this entity? '
                class_no = int(raw_input())
                for i in range(0, int(class_no)):
                    entity_class =  raw_input()
                    grams_to_check_dict[Entity]['matches'].append({'cateogry': entity_class})
                print 'grams_to_check is , '
                print grams_to_check_dict
                break

给出错误:

TypeError: string indices must be integers, not str

在第

grams_to_check_dict['key']['matches'].append({'cateogry': entity_class})

1 个答案:

答案 0 :(得分:1)

由于grams_to_check_dict['key']的值为Entity,因此它是一个字符串。 而你像字典一样威胁它!使用此命令grams_to_check_dict['key']['matches']

如果您想获得{'user_entered_Entity': {'matches': [{'cateogry': 'one'}, {'cateogry': 'two'}]}}而不是{'key': {'matches': [{'cateogry': 'one'}, {'cateogry': 'two'}]}} 删除行grams_to_check_dict['key'] = Entity 并更改

grams_to_check_dict['key']['matches'].append({'cateogry': entity_class})

grams_to_check_dict[Entity]['matches'].append({'cateogry': entity_class})

编辑:

>>> d={}
>>> d['key']={}
>>> d
{'key': {}}

>>> Entity=raw_input(' enter the key name :')
 enter the key name :newkey

>>> d={'%s'%Entity:{}}
>>> d
{'newkey': {}}