【问题标题】:How to convert a list with key value pairs to dictionary如何将具有键值对的列表转换为字典
【发布时间】:2019-06-07 22:59:57
【问题描述】:

我想遍历这个列表

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

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

提前感谢您的帮助。

【问题讨论】:

  • 该条目列表是否保证按该顺序排列,或者元素可以按任何顺序排列?
  • 输入中每个组的大小是否固定?如果不是,如何确定组边界?

标签: python list dictionary


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你可以这样做:

    dictionary = dict()
    all_dictionaries = []
    for index , value  in  [x.split(": ") for x in A] :
         if index in dictionary :
             all_dictionaries .append(dictionary )
             dictionary = dict()
         else :
           dictionary [index] = value
    all_dictonaries.append(dictionary)
    

    【讨论】:

      【解决方案3】:

      假设您的顺序始终相同,即 4 个一组。想法是使用 : 拆分字符串,然后创建键/值对并使用嵌套的 for循环。 .strip() 是去掉空格

      lst = ['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']
      
      answer = []
      
      for i in range(0, len(lst), 4):
          dic = {}
          for j in lst[i:i+4]:
              dic[j.split(':')[0]] = j.split(':')[1].strip() 
          answer.append(dic)
      
      # [{'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'}]
      

      列表推导式如下所示

      answer = [{j.split(':')[0]:j.split(':')[1].strip() for j in lst[i:i+4]} for i in range(0, len(lst), 4)]
      

      【讨论】:

        【解决方案4】:

        如果保证列表中数据的形式始终是问题示例中的形式,那么您可以这样做:

        L = ['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']
        
        A = []
        
        for i in range(0, len(L), 4):
          D = {}
          for p in L[i:i + 4]:
            k, v = map(str.strip, p.split(':'))
            D[k] = v
          A.append(D)
        
        from pprint import pprint
        pprint(A)
        

        输出:

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

        【讨论】:

          【解决方案5】:

          此解决方案假设每个组的大小正好是 4

          l = ['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']
          
          output = [dict(s.split(": ") for s in l[i:i+4]) for i in range(0, len(l), 4)]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-05
            • 1970-01-01
            • 2020-01-17
            • 2022-01-19
            相关资源
            最近更新 更多