0

I have dictionary,

d = [{
       'id': 1
       'a' : [11,12],
       'b' : [25,17],
       'c' : [13,18] 
}]

Here I want to write in csv with column headers as keys (id,a,b,c) and values as rows. Here I want to write first row has values (1,11,25,13) with keys (id,a,b,c) and second row will have values (1,12,17,18) with the same keys having id same for both rows. Meaning if my value has more than two values it needs to be written in csv in next row with same columns headers and same id.

I was trying something like this

CSV ="\n".join([k+','+",".join(v) for k,v in dict_data[0].items()])
print CSV

But again, the columns are coming as row, csv file id,1,(no value, i need 1 here) ---- Here id will not appear a,11,12 b,25,17 and they are coming as rows, i want id, a b as columns

4
  • 3
    Where is your code? Commented Jan 8, 2018 at 7:36
  • will your id key always be an int, or can it also be a list object? How regular is your data? Commented Jan 8, 2018 at 7:39
  • You can either use string manipulation to write a .csv, or use a library such as pandas that have methods that write .csv file, corresponding to your datas (you will need to format your data according to pandas of course). Commented Jan 8, 2018 at 7:39
  • 1
    Did you try to "transpose" the input data and use csv library? Commented Jan 8, 2018 at 7:46

3 Answers 3

2

I think Pandas DataFrame is your best shot. I have slightly modified your data to make id column as a list too -

d = {
       'id': [1],
       'a' : [11,12,13],
       'b' : [25,17],
       'c' : [13,18] 
}

import pandas as pd
df = pd.DataFrame.from_dict(d,orient='index').transpose()
df = df.fillna(method='ffill')
print(df)

Finally, just output it to a csv df.to_csv('output.csv', index=False)

Output -

id     a     b     c
0  1.0  11.0  25.0  13.0
1  1.0  12.0  17.0  18.0
2  1.0  13.0  17.0  18.0

It first creates a dataframe with NA values for missing and then replaces those NA values with the values in the previous row.

Sign up to request clarification or add additional context in comments.

1 Comment

List has no attribute values this is what I get
0

You can use DataFrame contructor with DataFrame.to_csv:

import pandas as pd

df = pd.DataFrame(d[0], columns=['id','a','b','c'])
print (df)
   id   a   b   c
0   1  11  25  13
1   1  12  17  18

and then:

df.to_csv(file, index=False)

All together:

pd.DataFrame(d[0], columns=['id','a','b','c']).to_csv(file, index_col=False)

3 Comments

Hey , values can be string as well.
Error while using code I get is arrays must all be same length
Problem is with sample data or real data dictionary?
0

Try from_dict for dataframe creation of pandas after converting id to a list:

import pandas as pd
d = [{ 'id': 1,
       'a' : [11,12],
       'b' : [25,17],
       'c' : [13,18] }]

# d['id'] = [d['id']] * len(d['a'])  # no need for this line; kept only because it is discussed in comments
df = pd.DataFrame.from_dict(d[0])  # if dict is in a list, use d[0]
print(df)

Output:

    a   b   c  id
0  11  25  13   1
1  12  17  18   1

To write to csv file:

df.to_csv("out.csv", index=False)

5 Comments

Hey,firstly the values can can be string.
No, it will still work: ["5"] * 5 produces ['5', '5', '5', '5', '5']. The list items are repeated, not arithmetically multiplied.
Actually, this code statement is not needed. The output remains same even if this statement is omitted.
Thanks, for the reply.Yes Dict is list, i used index[0] but having error arrays must all be same length
It works ok for me. There should be a comma after "1" .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.