我正在分析下面的财务报表,并试图从中创建字典。但我一直得到这个错误: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']
]
下面是我用来创建字典的代码:
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,我想使该列表的条目同时具有字典键和值。如果列表条目有多个条目,我希望将第一个条目设置为键,其余条目设置为值。我不确定我得到的错误是什么,以及为什么它会发生。你认为这是为什么?我该怎么解决
解释(更新)
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
中的值关联的键这应该可以做到:
相关问题 更多 >
编程相关推荐