【发布时间】:2021-05-07 03:23:29
【问题描述】:
我查找了“嵌套字典”和“嵌套列表”,但任何一种方法都有效。
我有一个具有以下结构的 python 对象:
[{
'id': 'productID1', 'name': 'productname A',
'option': {
'size': {
'type': 'list',
'name': 'size',
'choices': [
{'value': 'M'},
]}},
'variant': [{
'id': 'variantID1',
'choices':
{'size': 'M'},
'attributes':
{'currency': 'USD', 'price': 1}}]
}]
我需要输出的是以下扁平结构中的 csv 文件:
id, productname, variantid, size, currency, price
productID1, productname A, variantID1, M, USD, 1
productID1, productname A, variantID2, L, USD, 2
productID2, productname A, variantID3, XL, USD, 3
我尝试了这个解决方案:Python: Writing Nested Dictionary to CSV 或者这个:From Nested Dictionary to CSV File
我摆脱了[] 周围和内部data 和例如我使用了来自2 的代码 sn-p 并根据我的需要进行了调整。 IRL 我无法摆脱[],因为这是我调用 API 时得到的简单格式。
with open('productdata.csv', 'w', newline='', encoding='utf-8') as output:
writer = csv.writer(output, delimiter=';', quotechar = '"', quoting=csv.QUOTE_NONNUMERIC)
for key in sorted(data):
value = data[key]
if len(value) > 0:
writer.writerow([key, value])
else:
for i in value:
writer.writerow([key, i, value])
但是输出是这样的:
"id";"productID1"
"name";"productname A"
"option";"{'size': {'type': 'list', 'name': 'size', 'choices': {'value': 'M'}}}"
"variant";"{'id': 'variantID1', 'choices': {'size': 'M'}, 'attributes': {'currency': 'USD', 'price': 1}}"
有人可以帮帮我吗?
提前致谢
【问题讨论】:
-
你能告诉我们你写了什么引发了错误吗?
-
是的,我添加了使用的代码和错误
-
要么您对实际引发错误的位置感到困惑(根据您的代码,它应该位于
data[sessionId]),要么您发布的代码不完整 -
@c.Nivs 是的,你是对的,
data周围有[ ],会在data[sessionId]产生错误。我删除了[ ]并在writer.writerow([sessionId, item, ratings[item]])得到它。 -
@C.Nivs 我对其进行了一些调整,但输出仍然不令人满意... ^^ 和 IRL 我无法摆脱
[ ]因为这就是我从中得到的API 调用。
标签: python list csv dictionary nested