4

I have a dictionary. I am trying to join the values only. This is the dictionary:

d = {'x': 1, 'y': 2, 'z': 3}

My expected output is 123 (it should be 123 without any sorting).

The code I am using:

d = {'x': 1, 'y': 2, 'z': 3}
test = ' '.join(d.values())
print test

It is showing an error:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    test = ' '.join(d.values())
TypeError: sequence item 0: expected string, int found

I am using Python 2.x.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Codieroot
  • 697
  • 2
  • 7
  • 15

2 Answers2

20

Your values are not strings:

d = {'x': 1, 'y': 2, 'z': 3}
test = ''.join(str(x) for x in d.values())

As MosesKoledoye pointed out: the order of the keys is not guaranteed, so you might want to do something more elaborate if the order is important. Doing a str() on the integer values is vital in any case.

''.join(str(d[x]) for x in sorted(d))

The above will sort the values based on the sort order of the keys, and sorting by the values themselves is trivial.

Your output doesn't have a space between the digits either, so make sure you join on '', not on ' '.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anthon
  • 69,918
  • 32
  • 186
  • 246
  • You probably want to state it can't always be 123 without any sorting at least in Python 2 – Moses Koledoye Jun 18 '17 at 21:15
  • @MosesKoledoye I will thanks. – Anthon Jun 18 '17 at 21:15
  • @Anthon I was referring to the ones you just removed, just inside of `str.join`. So, `''.join((...))` only needs to be `''.join(...)`. – G_M Jun 18 '17 at 21:20
  • @Anthon I was just trying to be polite. It seemed unnecessary to leave that comment there after you made the edit. I would have left it there if I had known how amusing your reaction was going to be. – G_M Jun 18 '17 at 21:57
4

You need to map over the values with the string function:

d = {'x': 1, 'y': 2, 'z': 3}

test = ' '.join(map(str, d.values()))

Note that this solution will not return the values in sorted format i.e the numbers will not be in ascending order. If you want a sorted solution, however:

test = ' '.join(map(str, sorted(d.values())))
Ajax1234
  • 69,937
  • 8
  • 61
  • 102