仅将某些值加入字典列表

时间:2018-06-06 15:15:25

标签: python python-3.x list dictionary

如何从字典列表中的某些值创建字符串? 我想只加入词典中'first_name'和'last_name'的值。

[{"id": 1, "first_name": "John", "last_name": "Smith"},
 {"id": 1, "first_name": "Tom", "last_name": "Carry"},
 ...]

2 个答案:

答案 0 :(得分:1)

您可以使用简单的for循环:

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'}]

然后,要提取全名列表,您可以使用列表推导:

res = [i['full_name'] for i in L]

print(res)

['John Smith', 'Tom Carry']

答案 1 :(得分:1)

另一种简单的方法是:

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