Reputation: 29
How can make a string from certain values from a list of dictionaries ? I would like to only join the values of 'first_name' and 'last_name' from the dictionaries.
[{"id": 1, "first_name": "John", "last_name": "Smith"},
{"id": 1, "first_name": "Tom", "last_name": "Carry"},
...]
Upvotes: 0
Views: 45
Reputation: 26037
Another easy way would be:
lst = [{"id": 1, "first_name": "John", "last_name": "Smith"},
{"id": 1, "first_name": "Tom", "last_name": "Carry"}]
for x, y in [(d['first_name'], d['last_name']) for d in lst]:
print(f'{x} {y}')
# John Smith
# Tom Carry
Upvotes: 1
Reputation: 164773
You can use a simple for
loop:
L = [{"id": 1, "first_name": "John", "last_name": "Smith"},
{"id": 1, "first_name": "Tom", "last_name": "Carry"}]
for i in L:
i['full_name'] = '{0} {1}'.format(i['first_name'], i['last_name'])
print(L)
[{'id': 1, 'first_name': 'John', 'last_name': 'Smith', 'full_name': 'John Smith'},
{'id': 1, 'first_name': 'Tom', 'last_name': 'Carry', 'full_name': 'Tom Carry'}]
Then, to extract a list of full names, you can use a list comprehension:
res = [i['full_name'] for i in L]
print(res)
['John Smith', 'Tom Carry']
Upvotes: 1