jacosro
jacosro

Reputation: 539

Cannot concatenate 'str' and 'tuple' objects on dictionary

I am just trying to print the key and the value of a dictionary but I get the TypeError. The code:

def __str__(self):
    string = ""
    for key in self.dictionary:
        string += key, "-->", self.dictionary[key] + '\n'
    return string

I add for example the key 'key' and the value 'value', the content of the dictionary is correct:

{'key': 'value'}

But then I try to call the str method and get this:

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

I don't know why this error shows up, the key is a string just like the value

Upvotes: 0

Views: 2370

Answers (4)

SudoKid
SudoKid

Reputation: 439

The problem is with the , in your string format line.

You have this

string += key, "-->", self.dictionary[key] + '\n'

When it should be this

string += key + "-->" + self.dictionary[key] + '\n'

This is what you currently have:

def __str__(self):
    string = ""
    for key in self.dictionary:
        string += key + "-->" + self.dictionary[key] + '\n'
    return string

A simple way to do the same thing:

def __str__(self):
    return ''.join(['{}-->{}\n'.format(x, y) for x, y in self.dictionary.items()])

Same as above but using C strings:

def __str__(self):
    return ''.join(["%s-->%s\n" % (x, y) for x, y in self.dictionary.items()]

One liner using a lambda:

def __str__(self):
    return ''.join(map(lambda x: '{}-->{}\n'.format(x[0], x[1]), self.dictionary.items()))

Same as above but using C strings:

def __str__(self):
    return ''.join(map(lambda x: "%s-->%s\n" % (x[0], x[1]), self.dictionary.items())

Upvotes: 0

Dekel
Dekel

Reputation: 62556

Use the format method of the String object:

def __str__(self):
    string = ""
    for key in self.dictionary:
        string = "{}{}-->{}\n".format(string, key, self.dictionary[key])
    return string

Upvotes: 5

alecxe
alecxe

Reputation: 473853

You are actually trying to concatenate tuple with a string on this line (note the commas):

string += key, "-->", self.dictionary[key] + '\n'

I think you meant to simply concatenate key with --> with value and a newline:

string += key + "-->" + self.dictionary[key] + '\n'

Upvotes: 5

bigblind
bigblind

Reputation: 12867

This line is the problem:

string += key, "-->", self.dictionary[key] + '\n'

The commas between k, the arrow and the value make it into a tuple.

Try to change it into

string += key + "-->" + str(self.dictionary[key]) + '\n'

(you may need to wrap your key as str(key) as well, if you have keys that aren't strings.)

You can write this even cleaner as:

string += "%s-->%s\n" % (key, self.dictionary[key])

Upvotes: 7

Related Questions