我的数据结构来自Vimeo API
{'duration': 720,
'language': 'sv',
'link': 'https://vimeo.com/neweuropefilmsale/incidentbyabank',
'name': 'INCIDENT BY A BANK',
'user': {
'link': 'https://vimeo.com/neweuropefilmsales',
'location': 'Warsaw, Poland',
'name': 'New Europe Film Sales'
}
}
我想在
中进行transofrm[720, "sv", "http..", "incident.." "http..", "Warsaw", "New Europe.."]
将其加载到Google电子表格中。我还需要保持一致性值顺序。
PS。我看到类似的问题,但答案不在Python 3中
由于
答案 0 :(得分:1)
我将使用csv
模块创建一个类似于您的数据描述的CSV文件。
首先,我们应该为您的文件使用标题行,因此顺序并不重要,只有dict键才能执行:
import csv
# This defines the order they'll show up in final file
fieldnames = [
'name', 'link', 'duration', 'language',
'user_name', 'user_link', 'user_location',
]
# Open the file with Python
with open('my_file.csv', 'w', newline='') as my_file:
# Attach a CSV writer to the file with the desired fieldnames
writer = csv.DictWriter(my_file, fieldnames)
# Write the header row
writer.writeheader()
注意DictWriter
,这将允许我们根据键而不是顺序编写dicts(dicts在3.6之前是无序的)。上面的代码最终会得到一个这样的文件:
name;link;duration;language;user_name;user_link;user_location
然后我们可以添加行,但我们首先转换您的数据,因此密钥与上述字段名称匹配:
data = {
'duration': 720,
'language': 'sv',
'link': 'https://vimeo.com/neweuropefilmsale/incidentbyabank',
'name': 'INCIDENT BY A BANK',
'user': {
'link': 'https://vimeo.com/neweuropefilmsales',
'location': 'Warsaw, Poland',
'name': 'New Europe Film Sales'
}
}
for key, value in data['user'].items():
data['user_{}'.format(key)] = value
del data['user']
最终会得到data
字典,如下所示:
data = {
'duration': 720,
'language': 'sv',
'link': 'https://vimeo.com/neweuropefilmsale/incidentbyabank',
'name': 'INCIDENT BY A BANK',
'user_link': 'https://vimeo.com/neweuropefilmsales',
'user_location': 'Warsaw, Poland',
'user_name': 'New Europe Film Sales',
}
我们现在可以简单地将此作为整行插入CSV编写器,其他所有内容都自动完成:
# Using the same writer from above, insert the data from above
writer.writerow(data)
现在,只需将其导入您的Google电子表格即可:)
答案 1 :(得分:1)
这是一个使用递归的简单解决方案:
dictionary = {
'duration': 720,
'language': 'sv',
'link': 'https://vimeo.com/neweuropefilmsale/incidentbyabank',
'name': 'INCIDENT BY A BANK',
'user': {
'link': 'https://vimeo.com/neweuropefilmsales',
'location': 'Warsaw, Poland',
'name': 'New Europe Film Sales'
}
}
def flatten(current: dict, result: list=[]):
if isinstance(current, dict):
for key in current:
flatten(current[key], result)
else:
result.append(current)
return result
result = flatten(dictionary)
print(result)
说明:我们调用flatten()
直到达到字典的值,这不是字典本身(if isinstance(current, dict):
)。如果我们达到此值,我们会将其附加到result list
。它适用于任意数量的嵌套字典。
请参阅:How would I flatten a nested dictionary in Python 3?
我使用了相同的解决方案,但我已将result
集合更改为列表。