将python列表项转换为字典键值对



我正试图打开以下列表:

['06/07/20n 22,43€ gasn 34,70€ street toll, ' 08/07/20n 74,90€ street toll, ' 13/07/20n 78€ street tolln 157,90€ gas']

输入这样的字典:

{'06/07/20':['22,43€ gas', '34,70€ street toll'],'08/07/20':['74,90€ street toll'],'13/07/20':['78€ street toll', '157,90€ gas']}

我所做的是:


for i in parsf2:
if "/" in i:
new_dict[i]=i
elif "/" not in i:
new_dict[i]=i
else:
x.append(i)
print(new_dict)

我目前的结果是:

{'06/07/20n': '06/07/20n', '22,43€ gasn': '22,43€ gasn', '34,70€ street tolln': '34,70€ street tolln', 'n': 'n', '08/07/20n': '08/07/20n', '74,90€ street tolln': '74,90€ street tolln', '13/07/20n': '13/07/20n', '78€ street tolln': '78€ street tolln', '157,90€ gas': '157,90€ gas'}

如何轻松修复初学者的代码?

您可以进行

a = ['06/07/20n 22,43€ gasn 34,70€ street toll', ' 08/07/20n 74,90€ street toll', ' 13/07/20n 78€ street tolln 157,90€ gas']
d = {k.splitlines()[0] : list(map(str.strip, k.splitlines()[1:])) for k in a }

输出

{'06/07/20': [' 22,43€ gas', ' 34,70€ street toll'],
' 08/07/20': [' 74,90€ street toll'],
' 13/07/20': [' 78€ street toll', ' 157,90€ gas']}

尝试:

lst = [
"06/07/20n 22,43€ gasn 34,70€ street toll",
" 08/07/20n 74,90€ street toll",
" 13/07/20n 78€ street tolln 157,90€ gas",
]
out = {}
for v in lst:
s = v.split(maxsplit=1)
if len(s) == 2: 
k, v = s
out[k] = [w.strip() for w in v.splitlines()]
print(out)

打印:

{
"06/07/20": ["22,43€ gas", "34,70€ street toll"],
"08/07/20": ["74,90€ street toll"],
"13/07/20": ["78€ street toll", "157,90€ gas"],
}

编辑:简短解释:

我迭代lst的每个值,并将其拆分为日期(第一部分(和其余部分(使用str.splitmaxsplit=1参数(

然后,我将其余部分拆分为行(n(并去除空白,将结果存储在out字典中。

final_result = {}
for entry in parsf2:
entries = entry.split("n")
final_result[entries[0]] = entries[1:]
>>> final_result
{'06/07/20': [' 22,43€ gas', ' 34,70€ street toll'], ' 08/07/20': [' 74,90€ street toll'], ' 13/07/20': [' 78€ street toll', ' 157,90€ gas']}

您可以使用splitdict comprehension

In [1]: {i.split(maxsplit=1)[0]:i.split(maxsplit=1)[1].split('n') for i in lst}
Out[1]: 
{'06/07/20': ['22,43€ gas', ' 34,70€ street toll'],
'08/07/20': ['74,90€ street toll'],
'13/07/20': ['78€ street toll', ' 157,90€ gas']}

最新更新