Skip to main content
 首页 » 编程设计

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

2025年05月04日15yxwkf

我想遍历这个列表

['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',角色:'test2',描述:'test2'}]

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

提前感谢您的帮助。

请您参考如下方法:

无需事先知道每个dict有多少个key,可以遍历list,通过':'将每个字符串拆分成一个key和一个value,追加一个新的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 

因此给定存储在 lst 中的示例列表,output 将变为:

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