【问题标题】:How to convert list of strings to list of dictionaries in python如何将字符串列表转换为python中的字典列表
【发布时间】:2019-07-31 22:15:46
【问题描述】:

假设我在 Python 中有一个字符串列表:

['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 
 'Name: volume_xx111', 'Index: 3', 'Name: volume_xx11541', 'Index: 4', 
 'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']

如何将它们转换为字典列表,以便最终结果如下:

[
 {'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, 
 {'Name': 'volume_xx111', 'Index': '3'}, 
 {'Name': 'volume_xx11541', 'Index': '4'}, 
 {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6}
]

【问题讨论】:

  • 解决这个问题的方法太多了。答案只会变成一个人们喜欢的稻草民意调查。最好的办法是自己对这个主题进行一些研究,找到两三个,分析它们,确定它们是否适合你,然后尝试一下。如果您对尝试做的事情有具体问题,请联系我们。

标签: python list-comprehension dictionary-comprehension


【解决方案1】:

您需要在代码中决定如何将字符串分组到字典中。也许每个元素总是有 2 个元素,或者总是有一个 Name 条目,或者您只需要在以前每次看到一个键时创建一个新字典。

如果每个字典总是有 N 个元素,那么 iterate in chunks of that size:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

results = [
    dict(tuple(map(str.strip, entry.split(': '))) for entry in per_dict)
    for per_dict in chunks(inputlist, 2)
]

演示:

>>> from pprint import pprint
>>> inputlist = ['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 'Name: volume_xx111', 'Index: 3', 'Name: volume_xx11541', 'Index: 4', 'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']
>>> def chunks(l, n):
...     """Yield successive n-sized chunks from l."""
...     for i in range(0, len(l), n):
...         yield l[i:i + n]
...
>>> [
...     dict(tuple(map(str.strip, entry.split(': '))) for entry in per_dict)
...     for per_dict in chunks(inputlist, 2)
... ]
[{'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, {'Name': 'volume_xx111', 'Index': '3'}, {'Name': 'volume_xx11541', 'Index': '4'}, {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6'}]
>>> pprint(_)
[{'Index': '24', 'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37'},
 {'Index': '3', 'Name': 'volume_xx111'},
 {'Index': '4', 'Name': 'volume_xx11541'},
 {'Index': '6',
  'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10'}]

如果看到重复键是更好的方法,那么从包含空字典的列表result 开始;您将键值对添加到result[-1]。然后逐个处理您的字符串,将每个字符串拆分为':' 字符以创建键值对。如果键已经在最近的字典中找到,则开始一个新的空字典:

results = [{}]
for entry in inputlist:
    key, value = map(str.strip, entry.split(':'))  # removing surrounding whitespace
    if key in results[-1]:
        # start a new dictionary
        results.append({})
    results[-1][key] = value

通过检查 key 是否存在,NameIndex 条目是否交换不再重要。

演示:

>>> results = [{}]
>>> for entry in inputlist:
...     key, value = map(str.strip, entry.split(':'))  # removing surrounding whitespace
...     if key in results[-1]:
...         # start a new dictionary
...         results.append({})
...     results[-1][key] = value
...
>>> pprint(results)
[{'Index': '24', 'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37'},
 {'Index': '3', 'Name': 'volume_xx111'},
 {'Index': '4', 'Name': 'volume_xx11541'},
 {'Index': '6',
  'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10'}]

【讨论】:

    【解决方案2】:

    我的解决方案如下:

    lista = ['Name: volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index: 24', 
             'Name: volume_xx111', 'Index: 3', 
             'Name: volume_xx11541', 'Index: 4', 
             'Name: Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index: 6']
    result = []
    
    for n, item in enumerate(lista):
        if n % 2 == 0:
            result.append({'Name': item[item.find(':') + 2:],
                           'Index': lista[n + 1][lista[n + 1].find(':') + 2:]})
    print(result)
    

    有了这个输出:

    [{'Name': 'volume_test_add_volume_to_cg_2019_03_07-12_21_37', 'Index': '24'}, {'Name': 'volume_xx111', 'Index': '3'}, {'Name': 'volume_xx11541', 'Index': '4'}, {'Name': 'Volume_test_add_volume_mandatory_params_2019_03_06-16_50_10', 'Index': '6'}]
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多