【问题标题】:Python dictionary access ends up as a typeerrorPython 字典访问最终成为类型错误
【发布时间】:2021-04-19 22:03:58
【问题描述】:

我正在尝试使用 Python 3.9 和 VS Code 终端更改字典的特定部分,但在更改部分中,

 elif choice=='2':
                    part_name = input('Which part are you willing to change?\n(CaSe SeNsEtIvE)\nname--age--score--ID? ')
                    if part_name in list_keys:
                        new_value = input("New value? ")
                    else:
                        print('part not found!')
                        ending()
                    listname[final[part_name]] = new_value
                    ending()

当我尝试访问字典中的值时,它返回错误TypeError: string indices must be integers。有什么问题?请注意,strip_name.delspace 是我的一个模块,用于删除字符串中的空格。

import os, msvcrt, strip_name
list_keys, listname = ['name', 'age', 'score', 'ID'], {'AsgharAkbari':{'name':"Asghar Akbari",'age': 28,'score': 86,'ID':23897},'amirrezavavsari':{'name':"amirreza vavsari",'age':15,'score': 94,'ID':53614}}
   

 def delete():
        os.system('cls')
        print("which student are you willing to delete? (print back to go back)")
      
            del_name = input("enter fullname(CaSe SeNsEtIvE): ")
       
            final = strip_name.delspace(del_name)
            if final in listname.keys():
                choice = input('1- Delete fully\n2-change a part')
                if choice=='1':
                    del listname[final]
                    ending()
                elif choice=='2':
                    part_name = input('Which part are you willing to change?\n(CaSe SeNsEtIvE)\nname--age--score--ID? ')
                    if part_name in list_keys:
                        new_value = input("New value? ")
                    else:
                        print('part not found!')
                        ending()
                    listname[final[part_name]] = new_value
           

【问题讨论】:

    标签: python python-3.x dictionary typeerror


    【解决方案1】:

    part_name 被识别为字符串,因为在 Python 3 中 input 不检查数据类型。解决方案是将数据从输入转换为整数:

    part_name = int(input('foo'))
    

    【讨论】:

      【解决方案2】:

      在 listname[final[part_name]] 中,final 是一个字符串,而您正尝试使用同样是一个字符串的part_name 对其进行索引。也许你的意思是listname[final][part_name],它在listname 中的键final 处访问字典中键part_name 的值?

      【讨论】:

      • 谢谢。帮了我很多。所以它就像 C++ 中的多维数组?
      • @SorooshYadollahPour 不客气! python 中的字典就像 c++ 中的无序映射。或多维地图,因为您有一本包含字典的字典。
      • NO NO NO 我指的是调用部分。
      猜你喜欢
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多