Message Boards Message Boards

0
|
6459 Views
|
1 Reply
|
1 Total Likes
View groups...
Share
Share this post:

[?]  Export Association as a CSV file?

For this question I use a simple example. I have the following association

test = Association[{a -> x, b -> y, c -> z}]

the output is: <|a -> x, b -> y, c -> z|>

After I export this association:

Export["test.csv", test, "CSV"]

I want to import the same file

Import["test.csv"]

the result is: {{"<|a -> x, b -> y, c -> z|>"}}

And this is a string.

What I want is a list like: {{a,x},{b,y,{c,z}}.

What is the easist way to do this?

POSTED BY: Michiel van Mens

Take a look at the contents of the CSV file to understand what is happening.

CSV files store tables, not "dictionary type" data structures, such as associations.

The question is: what do you want to achieve?

Just store an arbitrary association? Use the WDX, MX or Package export formats. They handle any expression.

Just store an association in a portable format? The problem is that your association has symbols both as its keys and values. Other systems don't typically work with symbols. You'd need to have string keys, and e.g. numerical values. Then you could export to JSON (use the RawJSON format).

You still want a CSV? The problem is not only that CSV isn't suitable for symbols, it's also that it is meant to store tables, not dictionary type data structures. You could transform your association to a table.

In[37]:= KeyValueMap[List, test]
Out[37]= {{a, x}, {b, y}, {c, z}}

Then export:

ExportString[
 KeyValueMap[List, test],
 "CSV"
 ]

"\"a\",\"x\"
\"b\",\"y\"
\"c\",\"z\"
"

When you re-import, you still get a table of strings (not symbols), which you will need to post-process to get the desired result. For example,

Association[
 Rule @@@ 
  ImportString["\"a\",\"x\"\n\"b\",\"y\"\n\"c\",\"z\"\n", "CSV"]
 ]
POSTED BY: Szabolcs Horvát
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract