1

', '.join(strings) can be used to concatenate all strings in a list.

Now I have a list storing objects, and I'd like to join their names together. e.g.:

>>> a=[{'name': 'John', 'age': '21'},{'name': 'Mark', 'age': '25'}]
>>> a[0]['name'] + ', ' + a[1]['name']
'John, Mark'

Is there a simple way like join() above to do this?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Deqing
  • 14,098
  • 15
  • 84
  • 131
  • `', '.join([x['name'] for x in a])` I doubt there's anything simpler. – vaultah Jul 21 '14 at 05:31
  • `strings.join(', ')` is from JS, right? – vaultah Jul 21 '14 at 05:32
  • 1
    @vaultah It would be simpler in some sense to remove the square brackets in your answer, and just use `','.join(x['name'] for x in a)`. – Ray Toal Jul 21 '14 at 05:35
  • @RayToal brackets make the performance difference in case of `join`. – vaultah Jul 21 '14 at 05:37
  • Thanks @vaultah, you should post it as an answer, even you might think it is simple :) Can you elaborate why it has performance difference? – Deqing Jul 21 '14 at 05:39
  • Indeed the lists vs. generators will differ in performance. I was playing on "simpler" in terms of the number of characters in the solution and probably should have had a smiley. :) – Ray Toal Jul 21 '14 at 05:42
  • @Deqing Please check my answer now, I included a link to another answer where the reason for the performance difference is discussed. – thefourtheye Jul 21 '14 at 05:52

1 Answers1

3

You have list of dictionaries not list of objects. We can join them together like this

print ", ".join(d["name"] for d in a)

d["name"] for d in a is called a generator expression, str.join will get the values from the generator expression one by one and join all of them with , in the middle.

But, if the list of dictionaries is too big then we can create a list of strings ourselves and pass it to the str.join like this

print ", ".join([d["name"] for d in a])

Here, [d["name"] for d in a] is called list comprehension, which iterates through a and creates a new list with all the names and we pass that list to be joined with ,.


I just noticed the discussion in the comments section. Please check this answer to know, why List Comprehension is better than GenExp in string joining.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497