What types of dictionary key names can be in Python
- 2021-11-29 07:35:51
- OfStack
Today, when looking at other people's code, I found one thing, that is, I took the object as the key name of the dictionary, and took two objects (instances of classes) as the key name, and then looked it up:
Keys must be immutable, such as strings, numbers, or tuples.
Type of 1 key, list/dictionary is not allowed, but everything else is allowed
However, the Internet did not say whether other types can be used or not. I tried to write code:
class Person:
def __init__(self, name):
self.name = name
i = 5
s = 'abc'
t = (5,'a')
p = Person('Lily')
q = Person('xiao')
m = {'a':1, 'b':10}
lst = [1,2,3]
d = {}
d[i] = 'five'
d[s] = 'ABC'
d[t] = 'five-a'
d[p] = 'name:Lily'
# d[lst] = 'list : 1,2,3'
# TypeError: unhashable type: 'list'
d[p, q] = 'two people: Lily and xiao'
d[i,s,t,p,q] = 'all in key'
for k, v in d.items():
print(k, '=>', v)
Output:
5 = > five
abc = > ABC
(5, 'a') = > five-a
< __main__.Person object at 0x000001803EEF27F0 > = > name:Lily
( < __main__.Person object at 0x000001803EEF27F0 > , < __main__.Person object at 0x000001803EEF28D0 > ) = > two people: Lily and xiao
(5, 'abc', (5, 'a'), < __main__.Person object at 0x000001803EEF27F0 > , < __main__.Person object at 0x000001803EEF28D0 > ) = > all in key
2 Multiple objects can be used as key names, and different keys are in different order
print(d[p, q])
print(d[q, p])
Output:
two people: Lily and xiao
Traceback (most recent call last):File " < ipython-input-15-12aff481ab93 > ", line 1, in < module >
runfile('C:/Users/Xpeng/.spyder-py3/temp.py', wdir='C:/Users/Xpeng/.spyder-py3')File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)File "D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)File "C:/Users/Xpeng/.spyder-py3/temp.py", line 37, in < module >
print(d[q, p])KeyError: ( < __main__.Person object at 0x000001803EF58940 > , < __main__.Person object at 0x000001803EF58668 > )
3 The conclusion is "wrong":
(1) Except that the list can't be used as a key name, everything else can be used, and more than one can be put.
(2) I understand that lists are mutable, and other types are immutable. When an object is used as a key name, what is actually passed in is the address of the object, which is also immutable.
(3) When putting multiple keys in different order, the keys are different.
----Updated on April 7, 2020---
Thank you for reminding me twice.
(1) To be precise, the non-hashable type of list and dictionary (unhashable) cannot be used as key value, but the hashable type can be used as key.