Skip to content Skip to sidebar Skip to footer

How To Convert Json Rows To Columns

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: c

Solution 1:

Use 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]})

Solution 2:

You could try:

from collections import defaultdict
x = defaultdict(list)
for item in rows:
    forkey, value in item.items():
        x[key].append(value)

Solution 3:

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

Here, I am creating a new dict i.e 'new_rows'. Now iterating over the elements of 'rows', appending the values of each dict element to 'new_rows' keys

Post a Comment for "How To Convert Json Rows To Columns"