jac*_*sro 0 python dictionary typeerror
我只是试图打印键和字典的值,但我得到了TypeError.代码:
def __str__(self):
string = ""
for key in self.dictionary:
string += key, "-->", self.dictionary[key] + '\n'
return string
Run Code Online (Sandbox Code Playgroud)
我添加了例如键'key'和值'value',字典的内容是正确的:
{'key': 'value'}
Run Code Online (Sandbox Code Playgroud)
但后来我尝试调用str方法并得到这个:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dictionary.py", line 37, in list
print self.__str__()
File "dictionary.py", line 42, in __str__
string += key, "-->", self.dictionary[key] + '\n'
TypeError: cannot concatenate 'str' and 'tuple' objects
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会出现这个错误,关键是字符串就像值一样
这一行是问题所在:
string += key, "-->", self.dictionary[key] + '\n'
Run Code Online (Sandbox Code Playgroud)
k,箭头和值之间的逗号使它成为一个元组.
尝试将其更改为
string += key + "-->" + str(self.dictionary[key]) + '\n'
Run Code Online (Sandbox Code Playgroud)
(str(key)如果你的密钥不是字符串,你可能需要包装你的密钥.)
你可以写这个更干净的:
string += "%s-->%s\n" % (key, self.dictionary[key])
Run Code Online (Sandbox Code Playgroud)
您实际上是在尝试将元组与此行上的字符串连接起来(请注意逗号):
string += key, "-->", self.dictionary[key] + '\n'
Run Code Online (Sandbox Code Playgroud)
我认为你的意思是简单地将键-->与值和换行符连接起来:
string += key + "-->" + self.dictionary[key] + '\n'
Run Code Online (Sandbox Code Playgroud)
使用对象的format方法String:
def __str__(self):
string = ""
for key in self.dictionary:
string = "{}{}-->{}\n".format(string, key, self.dictionary[key])
return string
Run Code Online (Sandbox Code Playgroud)