我只是想打印键和字典的值,但我得到了typeerror。代码:
def __str__(self):
string = ""
for key in self.dictionary:
string += key, "-->", self.dictionary[key] + 'n'
return string
我添加了键"键"和值"值",字典的内容是正确的:
{'key': 'value'}
,但随后我尝试调用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
我不知道为什么会出现此错误,键是字符串,就像值
这一行是问题:
string += key, "-->", self.dictionary[key] + 'n'
k,箭头和值之间的逗号使其成元组。
尝试将其更改为
string += key + "-->" + str(self.dictionary[key]) + 'n'
(如果您的密钥不是字符串,则可能还需要将密钥包装为str(key)
。)
您可以将此更加清洁编写为:
string += "%s-->%sn" % (key, self.dictionary[key])
您实际上是在尝试与此行上的字符串相连(请注意逗号):
string += key, "-->", self.dictionary[key] + 'n'
我认为您是要简单地将键与-->
串联键,并具有newline:
string += key + "-->" + self.dictionary[key] + 'n'
使用String
对象的format
方法:
def __str__(self):
string = ""
for key in self.dictionary:
string = "{}{}-->{}n".format(string, key, self.dictionary[key])
return string
问题是在您的字符串格式行中使用,
。
你有这个
string += key, "-->", self.dictionary[key] + 'n'
应该是这个
string += key + "-->" + self.dictionary[key] + 'n'
这就是您当前拥有的:
def __str__(self):
string = ""
for key in self.dictionary:
string += key + "-->" + self.dictionary[key] + 'n'
return string
做同样事情的简单方法:
def __str__(self):
return ''.join(['{}-->{}n'.format(x, y) for x, y in self.dictionary.items()])
与上面相同,但使用C字符串:
def __str__(self):
return ''.join(["%s-->%sn" % (x, y) for x, y in self.dictionary.items()]
使用lambda的一个衬里:
def __str__(self):
return ''.join(map(lambda x: '{}-->{}n'.format(x[0], x[1]), self.dictionary.items()))
与上面相同,但使用C字符串:
def __str__(self):
return ''.join(map(lambda x: "%s-->%sn" % (x[0], x[1]), self.dictionary.items())