如何将具有键值对的列表转换为字典 [英] How to convert a list with key value pairs to dictionary
问题描述
我想遍历此列表
['name: test1', 'email: test1@gmail.com', 'role: test', 'description: test', 'name: test2', 'email: test2@gmail.com', 'role: test2', 'description: test2', 'name: test3', 'email: test3@gmail.com', 'role: test3', 'description: test3']
,并返回每个组的词典列表.例如.
and return a list of dictionaries for each group. E.g.
[{name: 'test', email:'test@gmail.com', role:'test', description:'test'}, {name: 'test2', email:'test2@gmail.com', role:'test2', description:'test2'}]
我尝试用,(逗号)分隔列表,并在其中搜索名称:".我可以返回一个字段,例如姓名,但正在努力链接到电子邮件,角色等.
I've tried splitting the list by , (comma) and searching it for 'name:'. I can return one field such as name, but am struggling to link to to the email, role, etc.
非常感谢您提前提供帮助.
Thanks for any help in advance.
推荐答案
无需事先知道每个字典具有的键数,就可以遍历列表,将每个字符串分成一个键和一个值,并按
Without having to know the number of keys each dict has in advance, you can iterate through the list, split each string into a key and a value by ': '
, appending a new dict to the list if the key is already in the last dict, and keep adding the value to the last dict by the key:
output = []
for key_value in lst:
key, value = key_value.split(': ', 1)
if not output or key in output[-1]:
output.append({})
output[-1][key] = value
,以便给定存储在lst
中的样本列表,output
将变为:
so that given your sample list stored in lst
, output
would become:
[{'name': 'test1',
'email': 'test1@gmail.com',
'role': 'test',
'description': 'test'},
{'name': 'test2',
'email': 'test2@gmail.com',
'role': 'test2',
'description': 'test2'},
{'name': 'test3',
'email': 'test3@gmail.com',
'role': 'test3',
'description': 'test3'}]
这篇关于如何将具有键值对的列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!