如何将JSON行转换为列 [英] How to convert JSON rows to columns
本文介绍了如何将JSON行转换为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基于行的JSON数据结构:
I have a JSON data structure that is row-based:
rows = [
{'name': 'tim', 'age': 113},
{'name': 'tess', 'age': 111},
]
我想转换为基于列的数据:
that I would like to convert to column-based data:
columns = {
'name': ['tim', 'tess'],
'age': [113, 111],
}
如果有很多行和列,执行此操作的最易读方法是什么?
What is the most readable way to do this if there are lots of rows and columns?
推荐答案
使用 collections.defaultdict
:
from collections import defaultdict
rows = [
{'name': 'tim', 'age': 113},
{'name': 'tess', 'age': 111},
]
d = defaultdict(list)
for r in rows:
for k, v in r.items():
d[k].append(v)
print(d)
# defaultdict(<class 'list'>, {'name': ['tim', 'tess'], 'age': [113, 111]})
这篇关于如何将JSON行转换为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文