Reputation: 1002
I want to convert this json to the below expected output, but I'm not getting what I want. Please help!
a = {
"k1": [
[
"xyz1",
"type1"
],
[
"xyz2",
"type2"
]
],
"k2": [
[
1,
"a"
],
[
2,
"b"
]
]
}
The expected output is:
k1,xyz1,type1
k1,xyz2,type2
k2,1,a
k2,2,b
Thank you for your help!!
Upvotes: 0
Views: 81
Reputation: 9941
With list comprehension:
pd.DataFrame([[k] + v for k, vs in a.items() for v in vs])
Output:
0 1 2
0 k1 xyz1 type1
1 k1 xyz2 type2
2 k2 1 a
3 k2 2 b
Upvotes: 1
Reputation: 2293
Assuming that your input format will never change, and that the output you're after is precisely:
[['k1', 'xyz1', 'type1'],
['k1', 'xyz2', 'type2'],
['k2', 1, 'a'],
['k2', 2, 'b']]
Then a solution with no dependencies is:
# list to hold our output
out_rows = []
# iterate over outer keys, which will form the first column
for i,j in a.items():
# iterate over inner array which will form each row of the output
for row in j:
# build our new row
out_row = [i]
# add the detail from the inner array row
out_row.extend(row)
# add this to our output
out_rows.append(out_row)
You can then put this in a dataframe if you'd like:
df = pd.DataFrame(out_rows)
Upvotes: 0