我的列表如下:
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 ': ''}
请帮助。
答案 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'}
说明:
您可以解决问题:
out = line.split(sep='.')
结果:
['Identified Cost - Securities', '', '', '', '', '', '', '', '', '', '', '', ' $ 8,038,909,658', '20 ']
第一个值将是我们的键。
line.replace(key, '')
结果:
............ $ 8,038,909,658.20
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)