【问题标题】:Python 3 - Dictionary.items str object has no attribute items errorPython 3 - Dictionary.items str 对象没有属性项错误
【发布时间】:2017-02-04 20:33:41
【问题描述】:

我是 Python 新手,我想通过命令行输入字典,并在下面的代码中打印密钥:

for line in sys.stdin:

    adict ={}
    line = line.strip()
    adict = line

    for key, value in adict.items():
        print(key)

我不断收到错误消息:AttributeError: 'str' object has no attribute 'items'。

当我尝试创建字典并打印它时,它会:

data = {}
data[str(0) + str(1)] = "A " +  str(0) + " " + str(1.0) 

for key, value in data.items():
    print(key)

为什么我无法从命令行输入字典并打印密钥?我正在获取字典输入 ({'01': 'A 0 1.0'}) 并将其存储在字典变量 adict 中。 adict 打印正确,但为什么我不能在其上使用 items()?我做错了什么吗?

【问题讨论】:

  • 你只是用字符串覆盖了你的字典!!!你能指望什么?您的数据的关键应该是什么?

标签: python python-3.x dictionary


【解决方案1】:

line 是一个字符串,而您只有 rebound adict 名称到剥离的字符串,所以您没有字典,而是一个字符串。

您可以改用ast.literal_eval 从输入的字符串构建您的字典:

import ast

adict = ast.literal_eval(input())

【讨论】:

    【解决方案2】:

    检查您的 adict 类型,看看它在代码中的变化:

    for line in sys.stdin:
    
        adict ={}
        line = line.strip() # line here is a string
        adict = line   # so adict will be a string
    
        for key, value in adict.items():  # string doesn't have item attribute
            print(key)
    

    【讨论】:

    • 谢谢。我从中明白了很多。但我的问题仍然存在。如果我是正确的,sys.stdin 中的 for 行始终是一个字符串。但我的输入是字典。如何从字符串中提取我的键值? split 似乎需要做很多工作,并且对于大量输入可能不正确。我该怎么办?
    • 看摩西的回答,他给你一个建议
    猜你喜欢
    • 2015-04-19
    • 2022-01-21
    • 2016-01-29
    • 1970-01-01
    • 2016-04-07
    • 2023-03-05
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多