11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonの配列や辞書をずっと使えるようにする小技

Last updated at Posted at 2019-08-29

モチベーション

Jupyter Notebookとかで重たい処理をしたり、DBから値を取ってきたりするのを毎回するのは非常に非効率。
ファイルとして保存する(永続化する)方が絶対いい。
pickleを使えばかなり簡単だった。

配列

ファイルとして保存する(永続化)

pkl_array.py
import pickle

fruits_array = []
fruits= ["apple","orange","melon"]
for fruit in fruits:
    fruits_array.append(fruit)
with open("fruits_array.pkl","wb") as f:
    pickle.dump(fruits_array, f)

読み込む

pkl_array2.py
import pickle

with open('fruits_dict.pkl', 'rb') as f:
    fruits_color_dict_pkl = pickle.load(f)
print(fruits_color_dict_pkl)
{'apple': 'red', 'orange': 'orange', 'melon': 'green'}

辞書

ファイルとして保存する(永続化)

pkl_dict.py
import pickle

fruits_color_dict = {}
fruits_color_dict["apple"] = "red"
fruits_color_dict["orange"] = "orange"
fruits_color_dict["melon"] = "green"

with open("fruits_dict.pkl","wb") as f:
    pickle.dump(fruits_color_dict, f)

読み込む

pkl_dict2.py
import pickle

with open('fruits_dict.pkl', 'rb') as f:
    fruits_color_dict_pkl = pickle.load(f)
print(fruits_array_pkl)
['apple', 'orange', 'melon']
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?