Reputation: 330
I'm trying to iterate through the following list of dictionaries to produce output:
authors = [
{'id': 1, 'name': 'Grace Hopper'},
{'id': 2, 'name': 'Karl Marx'}
]
expected output:
'Grace Hopper, Karl Marx'
My code is missing something:
for item in authors:
for author in item.values():
print(author)
Output:
1
Grace Hopper
2
Karl Marx
How to solve it using a simplefor
loop? How to do it using list compression?
Upvotes: 0
Views: 48
Reputation: 123463
Here's one way:
from operator import itemgetter
authors = [
{'id': 1, 'name': 'Grace Hopper'},
{'id': 2, 'name': 'Karl Marx'}
]
print(', '.join(map(itemgetter('name'), authors))) # -> Grace Hopper, Karl Marx
Upvotes: 1
Reputation: 71451
You can use str.join
:
d = [{'id': 1, 'name': 'Grace Hopper'}, {'id': 2, 'name': 'Karl Marx'}]
new_d = ', '.join([i['name'] for i in d])
Output:
'Grace Hopper, Karl Marx'
Upvotes: 5