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?

7
  • ', '.join([x['name'] for x in a]) I doubt there's anything simpler. Commented Jul 21, 2014 at 5:31
  • strings.join(', ') is from JS, right? Commented Jul 21, 2014 at 5: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). Commented Jul 21, 2014 at 5:35
  • @RayToal brackets make the performance difference in case of join. Commented Jul 21, 2014 at 5: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? Commented Jul 21, 2014 at 5:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.