Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将JSON行转换为列_Python_List_Dictionary_Pivot_Reshape - Fatal编程技术网

Python 如何将JSON行转换为列

Python 如何将JSON行转换为列,python,list,dictionary,pivot,reshape,Python,List,Dictionary,Pivot,Reshape,我有一个基于行的JSON数据结构: rows = [ {'name': 'tim', 'age': 113}, {'name': 'tess', 'age': 111}, ] 我想转换为基于列的数据: columns = { 'name': ['tim', 'tess'], 'age': [113, 111], } 如果有很多行和列,最可读的方法是什么?使用集合。defaultdict: from collections import defaultdict

我有一个基于行的JSON数据结构:

rows = [
    {'name': 'tim', 'age': 113}, 
    {'name': 'tess', 'age': 111},
]
我想转换为基于列的数据:

columns = {
    'name': ['tim', 'tess'],
    'age': [113, 111],
}

如果有很多行和列,最可读的方法是什么?

使用
集合。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]})
从集合导入defaultdict
行=[
{'name':'tim','age':113},
{'name':'tess','age':111},
]
d=默认DICT(列表)
对于行中的r:
对于r.items()中的k,v:
d[k]。追加(v)
印刷品(d)
#defaultdict(,{'name':['tim','tess'],'age':[113111]})
您可以尝试:

from collections import defaultdict
x = defaultdict(list)
for item in rows:
    for key, value in item.items():
        x[key].append(value)
在这里,我创建了一个新的dict,即“new_rows”。现在迭代“rows”元素,将每个dict元素的值附加到“new_rows”键

new_rows={'name':[],'age':[]}
for row in rows:
    new_rows['name'].append(row['name'])
    new_rows['age'].append(row['age'])