【问题标题】:Getting 'Attribute Error - Str has no attribute GET'获取“属性错误 - Str 没有属性 GET”
【发布时间】:2020-09-17 10:21:13
【问题描述】:
我正在尝试编写这个小程序,但由于某种原因,我在这部分停滞不前。
我希望代码打印“随机答案”和“另一个答案”,但它最终给了我一个属性错误。有什么帮助吗?谢谢..
这是代码。
dictionary = {
'one':{'random':'random answer'},
'two':{'random':'another answer'}
}
for item in dictionary:
print(item.get('random'))
【问题讨论】:
标签:
python
python-3.x
list
dictionary
get
【解决方案1】:
试试这个。
dictionary = {
'one':{'random':'random answer'},
'two':{'random':'another answer'}
}
for key, item in dictionary.items():
print(item.get('random'))
【解决方案2】:
要遍历字典,您可以使用dictionary.items(),它会为您提供一个键值对元组。你可以把它们带到item, value。然后,您可以使用value.get(another_key)
dictionary = {
'one': {'random': 'random answer'},
'two': {'random': 'another answer'}
}
# item -> 'one' and value -> '{'random': 'random answer'}'
# value will be the dictionary on which you can call get function
for item, value in dictionary.items():
print(value.get('random'))
【解决方案3】:
如果你在 Python 中迭代一个 dict,你实际上是在迭代字典的键,而不是键值对。因此,在您的代码项中是关键,因此 get('random') 失败。
要遍历键值对,您可以使用.items() 方法。这样,您将遍历键值对的元组:
for key, value in dictionary.items():
print(value.get('random'))