python - 字典问题(TypeError : string indices must be integers)

标签 python python-3.x dictionary

所以,我是这个网站的新用户,我的字典功能有问题。

den = {
    'first_name': 'den',
    'last_name': 'elc',
    'age': '16',
    'city': 'slovakia',
}
for user, user_info in den.items():
    nameo = user_info['first_name']
    namei = user_info['last_name']
    age = user_info['age']
    city = user_info['city']
    print(f"\tFirst name:{nameo}")
    print(f"\tLast_name:{namei}")
    print(f"\tAge:{age}")
    print(f"\tCity:{city}")
Python 打印此 TypeError:
    Traceback (most recent call last):
  File "D:/PyCharm Community/pycharm/venv/Test.py", line 15, in <module>
    nameo = user_info['first_name']
TypeError: string indices must be integers
任何假设?

最佳答案

在这种情况下,如果您有一个字典数组,则不需要 for 循环,那么您需要考虑使用 for 循环。在这里你可以简单地做如下。

den = {
    'first_name': 'den',
    'last_name': 'elc',
    'age': '16',
    'city': 'slovakia',
}
print(f"\tFirst name:{den['first_name']}")
print(f"\tLast_name:{den['last_name']}")
print(f"\tAge:{den['age']}")
print(f"\tCity:{den['city']}")

关于python - 字典问题(TypeError : string indices must be integers),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69325747/

相关文章:

python - 带单引号的字符串提取

python - 如何快速撤销 turtle ?

python - 如何迭代和修改字典中的值?

python - 使用Python包将子包中的类导入主命名空间

python - 创建virtualenv时找不到满足需求requirements.txt的版本

python - python中的正则表达式搜索

python-3.x - matplotlib 使用figure.canvas.draw() 和figure.savefig() 抛出错误: "ValueError: Expected 2-dimensional array, got 1"

python - 映射和合并来自另一个数据框的值

python - 将字符串转换为具有正确类型的字典变量

python - 使用 Python 比较 UTC 时间和东部时间