0

I have a simple python dictionary in format:

{"key1":1,"key2":42,"key3":"foo"}

And would like to store in a csv file in which the keys are the headers and the values the cell values of the second row:

| "key1"  | "Key2" | "key3" |  
| 1       | 42     | "foo" |

the csv file will only have 2 rows.

I think it is possible using csv and python but can't find the correct approach (should be so easy). My rows/columns are always swapped.

jpp
  • 159,742
  • 34
  • 281
  • 339
Rutger Hofste
  • 4,073
  • 3
  • 33
  • 44
  • 1
    Maybe you can find what you need in this link : https://stackoverflow.com/questions/10373247/how-do-i-write-a-python-dictionary-to-a-csv-file – Nherv Sep 12 '18 at 15:21
  • please let me know if I should mark as duplicate and remove or leave this Q here. – Rutger Hofste Sep 12 '18 at 15:25
  • 1
    @RutgerHofste, I suggest you look at the answers and if you think they are straightforward to derive from the dup then accept the dup. This question does IMO have a small twist in that the input is neither a list of dictionaries, nor a dictionary with list values. – jpp Sep 12 '18 at 15:26
  • do you want a csv or pipe separated? – Stael Sep 12 '18 at 15:28
  • TLDR: csv is fine for now. the objective is to ingest a geopackage into google bigquery. I split up the features in the geopackage and convert the geometry to Well Known Text. A fancier approach would use Apache Beam but I will stcik to CSV for now. CSVs are uploaded to google cloud and bigquery can process them in parallel.(also, I spent too long reading Apache beam docs today that I could't figure out the easy stuff anymore.) – Rutger Hofste Sep 12 '18 at 15:31

4 Answers4

2

Assuming you dict name as d

pd.Series(d).to_frame().T
Out[55]: 
  key1 key2 key3
0    1   42  foo
#pd.Series(d).to_frame().T.to_csv()
BENY
  • 317,841
  • 20
  • 164
  • 234
2

Here's one way:

df = pd.DataFrame([d])

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

print(df)

   key1  key2 key3
0     1    42  foo

Notice the pd.DataFrame constructor accepts a list of dictionaries. Here the list happens to have only one dictionary, but this is sufficient.

jpp
  • 159,742
  • 34
  • 281
  • 339
0

Obvious answers have already been posted. Give a shot at numpy. Also, it will not regard the ordering.

import numpy as np
d={"key1":1,"key2":42,"key3":"foo"}
a=np.array([d.keys()])
b=np.array([d.values()])
x=np.concatenate([a,b],0)

np.savetxt('x.csv',x,delimiter=',',fmt='%s')
mad_
  • 8,121
  • 2
  • 25
  • 40
0

you can give it a try like this too

d = {"key1":1,"key2":42,"key3":"foo"}

df = pd.DataFrame.from_dict(d, orient='index').T
print(df)
  key1 key2 key3
0    1   42  foo
user96564
  • 1,578
  • 5
  • 24
  • 42