Python-原始文本到字典列表

时间:2019-04-03 03:09:46

标签: python dictionary

我有以下字符串需要转换为字典列表。

'"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018"," 23.19"," 2.13"," 1.32":"08-Jan-2019"," 22.70"," 5.22"," 1.02":'

执行此操作的pythonic方法是什么?键为"Date","Volume/Length","Length/Width","Weight gm"

3 个答案:

答案 0 :(得分:1)

首先,将字符串转换为嵌套的list,其中每个内部list代表一行:

import re

string = '"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018","       23.19","        2.13","        1.32":"08-Jan-2019","       22.70","        5.22","        1.02":'

nested_list = [[value.strip() for value in row.replace('"', '').split(',')] for row in string.strip(':').split(':')]

# Colons divide rows, so there shouldn't be any at the ends

然后转置嵌套的list,以使每个内部list现在表示一个。在每个列中,第一个元素是列名,其余元素是该列中的值。按照这种模式,我们可以执行切片以获取最终dict的键值对:

transposed_list = list(zip(*nested_list))
result = {column[0]: column[1:] for column in transposed_list}

# This part can be changed to list(column[1:]) if you want the inner elements to be lists

print(result)

输出:

{'Date': ('08-Dec-2018', '08-Jan-2019'), 
 'Volume/Length': ('23.19', '22.70'), 
 'Length/Width': ('2.13', '5.22'), 
 'Weight gm': ('1.32', '1.02')}

答案 1 :(得分:1)

首先将键提取为列表,然后将值提取为列表列表

s = '"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018","       23.19","        2.13","        1.32":"08-Jan-2019","       22.70","        5.22","        1.02":'

rows = s.split(':')
keys = rows[0].replace('"','').split(',')
# List of all keys
print(keys)
#['Date', 'Volume/Length', 'Length/Width', 'Weight gm']

values = []
for i in range(1,len(rows)-1):
    elems = rows[i].split(',')
    value = []
    for elem in elems:
        parsed_elem = elem.replace('"','').strip()
        value.append(parsed_elem)
    values.append(value)
#List of all values, as a list of lists
print(values)
#[['08-Dec-2018', '23.19', '2.13', '1.32'], ['08-Jan-2019', '22.70', '5.22', '1.02']]

此后,您可以使用键和值将其转换为字典列表

dict_list = []
for value in values:
    dct = {}
    for idx, key in enumerate(keys):
        dct[key] = value[idx]
    dict_list.append(dct)
print(dict_list)
#{'Date': '08-Dec-2018', 'Volume/Length': '23.19', 
#'Length/Width': '2.13', 'Weight gm': '1.32'}, 
#{'Date': '08-Jan-2019', 'Volume/Length': '22.70', 
#'Length/Width': '5.22', 'Weight gm': '1.02'}]

答案 2 :(得分:0)

您可以尝试

input_str = '"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018","       23.19","        2.13","        1.32":"08-Jan-2019","       22.70","        5.22","        1.02":'

input_str_formatted = input_str.replace('"', '')
input_list = input_str_formatted.split(':')

key_list = input_list[0].split(',')
val_list_1 = map( lambda x: x.strip() , input_list[1].split(',') )
val_list_2 = map( lambda x: x.strip() , input_list[2].split(',') )

result_dict = { key_list[i] : ( val_list_1[i], val_list_2[i] ) for i in range(len(key_list)) }

希望有帮助。