如何将具有键值对的列表转换为字典

Les*_*dge 8 python dictionary list

我想遍历这个列表

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

并返回每个组的字典列表。例如

[{name: 'test', email:'test@gmail.com', role:'test', description:'test'}, {name: 'test2', email:'test2@gmail.com', role:'test2', description:'test2'}]

我试过用 , (逗号)分割列表并搜索“名称:”。我可以返回一个字段,例如姓名,但很难链接到电子邮件、角色等。

提前感谢您的任何帮助。

blh*_*ing 5

无需事先知道每个 dict 的键数,您可以遍历列表,将每个字符串拆分为一个键和一个值': ',如果键已经在最后一个 dict 中,则将新的 dict 添加到列表中,以及通过键继续将值添加到最后一个字典:

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
Run Code Online (Sandbox Code Playgroud)

因此,鉴于您存储在 中的样本列表lstoutput将变为:

[{'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'}]
Run Code Online (Sandbox Code Playgroud)