解析财务报表时无法解决字典更新值错误

时间:2018-12-10 04:46:20

标签: python python-3.x

我正在解析以下财务报表,并尝试从中创建字典。但我不断收到此错误: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,则我想在该列表的条目中同时包含其字典键和值。如果列表条目有多个项目,我想将第一个条目作为键,将其余条目作为值。我不确定出现的错误是什么,以及为什么会发生。您为什么认为这种情况正在发生,我该如何解决?

2 个答案:

答案 0 :(得分:0)

here所述,update()方法使用来自字典对象或键/值对的可迭代对象中的元素来更新字典。您收到一条错误消息,因为您尝试更新字典而未指定与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})

答案 1 :(得分:0)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static', 'static_dirs'),
    )

说明(更新):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']]时,列表项将变为'key': ['foo', 'bar', 'foo2', 'bar2']。另外,我添加了if语句来检查密钥是否已经存在。

相关问题