分析财务状态时无法解决字典更新值错误

2024-05-13 18:11:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析下面的财务报表,并试图从中创建字典。但我一直得到这个错误:ValueError: dictionary update sequence element #0 has length 1; 2 is required

以下是财务报表:

[[XXX XXX LTD.'],
 ['Statement of Loss and Retained Earnings'],
 ['For the Year Ended May', 'XX,', 'XXXX'],
 ['Unaudited - See Notice To Reader'],
 ['XXXX', 'XXXX'],
 ['REVENUE', 'XXX,XXX,XXX', 'XXX,XXX,XXX']
]

下面是我用来创建字典的代码:

Python 3.6版

    for temp in cleaned_list:
        if len(temp) == 1:
            statement[temp[0]] = temp[0]
        elif len(temp) > 1:
            statement[temp[0]] = {}
            for temp_1 in temp[1:]:
                statement[temp[0]].update(temp_1)

如果列表的长度为1,我想使该列表的条目同时具有字典键和值。如果列表条目有多个条目,我希望将第一个条目设置为键,其余条目设置为值。我不确定我得到的错误是什么,以及为什么它会发生。你认为这是为什么?我该怎么解决


Tags: in列表fordictionarylen字典错误update
2条回答
statement = {}    
for temp in cleaned_list:
    if len(temp) == 1:
        statement[temp[0]] = temp[0]
    elif len(temp) > 1:
        if temp[0] in statement:
            statement[temp[0]].extend(temp[1:])
        else:
            statement[temp[0]] = temp[1:] 

解释(更新)statement.update()替换键中的值,同时您已经用statement[temp[0]] = {}重新设置字典键对。因此,似乎您不想更新值,而是附加列表项。我使用extend(),这样您就不会有像'key': ['foo', 'bar', ['foo2', 'bar2']]这样的列表项的值列表,而在使用extend()时,它将变成'key': ['foo', 'bar', 'foo2', 'bar2']。另外,我添加了if语句来检查密钥是否已经存在

here所述,update()方法使用来自dictionary对象或键/值对的iterable对象的元素更新dictionary。您将收到一条错误消息,因为您试图更新字典,但没有指定与temp_1中的值关联的键

这应该可以做到:

statement={}
for temp in cleaned_list:
    key=temp[0]
    statement.update({key:None})
    if len(temp)==1:
        value=key
        statement.update({key:value})
    elif len(temp) > 1:
        values=temp[1:]
        statement.update({key:values})

相关问题 更多 >