What is the most efficient way to load a dictionary in Python?

I have a Python dictionary of size ~ 1000 entries. A script will be called repeatedly, that will want to parse the string and see if any keys in the string match. If they do, it will require certain actions based on the key and value.

Which one is faster?

1) Store the dictionary in the MySQL database and then read the database every time the script is called?

2) Save the dictionary in a Python script and import it every time? (for example, create a file that contains nothing but dictionary initialization)

3) Save the dictionary in a text file and import it every time? (either a flat text file or a serialized data file using cpickle)

Just look for the best practice here.

+3
source share
3 answers

You can create a .py Python file that simply assigns the dictionary a name. Save the file. Compile the file in .pyc, then load it as a module, when necessary, with your main Python script.

You get the advantage of maintaining a readable textual representation of your dict for maintenance / debugging, the download speed of the .pyc file, and the simplicity of its standard Python.

+1
source

, python . ? , , , , - .

shelve . , , (3). anydbm. , , , .

-, 1) 3) . , , . 2) dict.

0

( ) :

    D = dict(zip(range(100),range(100)))
0

Source: https://habr.com/ru/post/1777153/


All Articles