在python中重新购买json

2024-09-23 10:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有当前的json格式:

data = [{'Content': 'This is the content', 'Title': 'Title1'},{'Content': 'I am content', 'Title': 'Title2'}, {'Content': 'This is more content', 'Title': 'Title3'}]

要将其转换为以下格式吗

data = {"Title":["Title1", "Title2", "Title3"], "Content":["This is the content","I am content","This is more content"]}

Tags: thejsondatatitleismore格式content
1条回答
网友
1楼 · 发布于 2024-09-23 10:19:42

只需迭代列表并将每个键、值对附加到新字典:

from collections import defaultdict
data = [{'Content': 'This is the content', 'Title': 'Title1'},{'Content': 'I am content', 'Title': 'Title2'}, {'Content': 'This is more content', 'Title': 'Title3'}]
result = defaultdict(list)
for elem in data:
  for k,v in elem.iteritems():
    result[k].append(v) 

相关问题 更多 >