Use list-keyed dict in Python

In Python, the list type cannot be a dictionary key.

key = [1, 2, 3]
table = {key: 1}  #error

The reason is that the list type can change its state. For example

key1 = [1]
key2 = [2]
table = {key1: 1, key2: 2}
key1[0] = 2

It would be a problem if you could do something like that. But I want to use the array as a key! In such a case, use tuple.

Library

Libraries that handle their own arrays include numpy and sympy. What is the treatment in these? Whether or not an object can be used as a key depends on whether or not there is a `` `hash``` function, so let's take a look.

from sympy import Matrix, ImmutableMatrix
import numpy as np

# sympy
Matrix([1, 2]).__hash__  # None
ImmutableMatrix([1, 2]).__hash__  # not None

# numpy
a = np.array([1, 2])
a.__hash__  # None
a.flags.writeable = False
a.__hash__  # None

So, it was useless even if it was not writable with numpy. Well, it's natural because it can be returned. .. (By the way, it seems that you can copy with as_immutable of sympy etc. Even if you make changes to the original, the result will not change.)

Recommended Posts

Use list-keyed dict in Python
Use config.ini in Python
Use dates in Python
Use Valgrind in Python
Use profiler in Python
Let's use def in python
Use let expression in Python
Use Measurement Protocol in Python
Use callback function in Python
Use parameter store in Python
Use HTTP cache in Python
Use MongoDB ODM in Python
Use Random Forest in Python
Use regular expressions in Python
Use Spyder in Python IDE
Use fabric as is in python (fabric3)
How to use SQLite in Python
Use rospy with virtualenv in Python3
How to use Mysql in python
Use Python in pyenv with NeoVim
How to use ChemSpider in Python
How to use PubChem in Python
Use OpenCV with Python 3 in Window
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
[Introduction to Python] How to use class in Python?
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Use print in a Python2 lambda expression
Meta-analysis in Python
Unittest in python
Easily use your own functions in Python
Epoch in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Easy way to use Wikipedia in Python
Python Dict category
Plink in Python
Constant in python
Don't use \ d in Python 3 regular expressions!
Lifegame in Python.
FizzBuzz in Python
How to use __slots__ in Python class
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
Use pathlib in Maya (Python 2.7) for upcoming Python 3.7
nCr in Python.
format in python