如何将具有键值对的列表转换为字典 [英] How to convert a list with key value pairs to dictionary

查看:425
本文介绍了如何将具有键值对的列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历此列表

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

推荐答案

无需事先知道每个字典具有的键数,就可以遍历列表,将每个字符串分成一个键和一个值,并按,如果密钥已经在最后一个字典中,则将新的dict添加到列表中,并继续通过该键将值添加到最后一个字典中:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆