Nourless
Nourless

Reputation: 854

How to transfer list from Python to Julia?

In Python I created a 3d list of data which I want to have access to in Julia. I wonder how to do that conveniently. If doing by writing in text file, how to parse it from julia? Or maybe there are specialized solutions for that, such as feather for dataframes?

For example, in python:

a = [[[0, 1]], [[1, 0.5], [2, 0.5]]]
save_to_convenient_for_parsing_file(a, filename)

in julia:

a = read_from_convenient_for_parsing_file(filename)
a
>2-element Vector{Vector{Vector{Float64}}}:
 [[0.0, 1.0]]
 [[1.0, 0.5], [2.0, 0.5]]

In that example, how save_to_convenient_for_parsing_file and read_from_convenient_for_parsing_file should look?

Upvotes: 3

Views: 651

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

One of the most natural ways to store objects in Python is pickle and it is supported in Julia:

import pickle
with open("a.pkl","wb") as f:
    pickle.dump(a,f)

And now you can do:

julia> using Pickle

julia> Pickle.load("a.pkl")
2-element Vector{Any}:
 Any[Any[0, 1]]
 Any[Any[1, 0.5], Any[2, 0.5]]

Note that an equivalent of Python's list is a Julia's vector of Any values as lists in Python are not typed.

A more universal format would be BSON:

import bson
with open("a.bson","wb") as f:
   f.write(bson.dumps({"a":a}))
julia> using BSON

julia> BSON.load("a.bson")
Dict{Symbol, Any} with 1 entry:
  :a => Any[Any[Any[0, 1]], Any[Any[1, 0.5], Any[2, 0.5]]]

Upvotes: 3

Related Questions