LSM
LSM

Reputation: 330

What is the best way to interact with the values of a dictionary list and save as string?

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

Answers (2)

martineau
martineau

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

Ajax1234
Ajax1234

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

Related Questions