我正在解析下面的财务报表并试图从中创建字典 . 但我一直收到这个错误: 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 回答
说明(更新):
statement.update()
替换键中的值,同时您已经使用statement[temp[0]] = {}
重新设置字典键对 . 因此,您似乎不想更新值,而是附加列表项 . 我使用extend()
,因此你没有像'key': ['foo', 'bar', ['foo2', 'bar2']]
这样的列表项的值列表,当使用extend()
时,它将变为'key': ['foo', 'bar', 'foo2', 'bar2']
. 另外,我添加了if语句来检查密钥是否已经存在 .详细here,
update()
方法使用字典对象中的元素或键/值对的可迭代对象更新字典 . 您收到一条错误消息,因为您尝试更新字典而未指定与temp_1
中的值关联的键 .这应该是诀窍: