如何根据指定字符将列表值拆分为字典?

时间:2020-09-08 15:03:27

标签: python-3.x list dictionary

我的列表如下:

test1 = "['Identified Cost - Securities............ $ 8,038,909,658.20 ',
          'Identified Cost - Late Loan Fundings.... $ .00 ]"

我需要如下字典:

"{Identified Cost - Securities : $ 8,038,909,658.20, 
  Identified Cost - Late Loan Fundings : $ .00}"

我尝试使用以下代码进行转换:

def Convert(lst): 
    res_dct = {lst[i]: "" for i in range(0, len(lst), 2)} 
    return res_dct 
test2 = Convert(test1)

我听从了字典。

{'Identified Cost - Securities............          $  8,038,909,658.20      ': '',
 'Identified Cost - Swaps.................                       $  .00      ': ''}

请帮助。

2 个答案:

答案 0 :(得分:0)

尝试执行以下代码:

test1 = ['Identified Cost - Securities............ $ 8,038,909,658.20 ', 'Identified Cost - Late Loan Fundings.... $ .00']
# creating a dictionary to unpack the list and store the data as per you require
temp_dict = {}
for test in test1:
    temp = test.rsplit("$", 1)
    temp_dict.update({temp[0].strip(): ("$" + temp[1]).strip()})

注意:基于最后一次出现的“ $”拆分列表值,并使用存储在临时变量的第0和第1索引位置的值更新字典

答案 1 :(得分:0)

简短答案:


def convert(lst):
    res_dct = dict((line.rsplit('$')[0].replace('.', ''), '$' + line.rsplit('$')[1].rstrip()) for line in lst if line.rsplit('$'))
    return res_dct


test1 = ['Identified Cost - Securities............ $ 8,038,909,658.20 ',
         'Identified Cost - Late Loan Funding.... $ .00']

test2 = convert(test1)

输出:

{'Identified Cost - Securities ': '$ 8,038,909,658.20', 'Identified Cost - Late Loan Funding ': '$ .00'}

说明:


您可以解决问题:

    1. 用'。'分隔字符串:
out = line.split(sep='.')

结果:

['Identified Cost - Securities', '', '', '', '', '', '', '', '', '', '', '', ' $ 8,038,909,658', '20 ']

第一个值将是我们的键。

    1. 从原始行中删除我们的键值
line.replace(key, '')

结果:

............ $ 8,038,909,658.20 
    1. 用'$'分隔字符串并删除正确的空格
8,038,909,658.20

如果将它们全部合并,结果:

{'Identified Cost - Securities': '$  8,038,909,658.20', 'Identified Cost - Late Loan Funding': '$  .00'}

代码:


def convert(lst):
    res_dct = {}

    for line in lst:
        out = line.split(sep='.')
        key = out[0]
        val = '$ ' + line.replace(key, '').split('$')[1].rstrip()
        res_dct[key] = val

    return res_dct


test1 = ['Identified Cost - Securities............ $ 8,038,909,658.20 ',
         'Identified Cost - Late Loan Funding.... $ .00']

test2 = convert(test1)