以列表作为值的字典,只需要第一个元素,如 "code:%"

Dictionary with list as values and only want the first element like "code:%"

所以我有一本包含数据的字典

dict = {1:["code: 1", "date: 01-01-2000", "date: 01-02-2000", "date: 01-03-2000", "spent: 20$"]}

我想要得到这个输出:

{1:["code: 1",  "date: 01-01-2000", "spent: 20$"]}

所以基本上我只想要第一个具有“日期:”的元素和其余元素

我怎样才能得到这个?

d = {1:["code: 1", "date: 01-01-2000", "date: 01-02-2000", "date: 01-03-2000", "spent: 20$"]}
a=[]
x=d[1][0:2]
y=d[1][-1]
a.append(x)
x.append(y)
output={1:x}
print(output)

尝试:

dct = {
    1: [
        "code: 1",
        "date: 01-01-2000",
        "date: 01-02-2000",
        "date: 01-03-2000",
        "spent: 20$",
    ]
}

out = {}
for k, v in dct.items():
    tmp = {}
    for i in reversed(v):
        tmp[i.split(":")[0]] = i
    out[k] = list(reversed(tmp.values()))

print(out)

打印:

{1: ['code: 1', 'date: 01-01-2000', 'spent: 20$']}