All -
I have a very basic question today ... but it has been preventing me from moving on productively in my programming, so I am posting it here.
I want to create a dictionary that takes a dictionary as a key. Presumably I can only pass a reference to the dictionary as key ... only I don't know how to do that in Python. Here is a toy reduction of what I am trying to do:
def test( dict ):
a={}
b={1:1}
a[ dict ] = b
return a
a = {0:0}
print test( a )
I would like b to be a dictionary of the form { {0:0} : {1:1} }.
Any help with this is much appreciated.
Kind regards -
Pat
Keys for dictionaries must be hashable items; unfortunately, dictionaries themselves are not hashable (they are mutable, which disqualifies them from being hashable).
Use their item list, converted to a sorted tuple, instead:
a[tuple(sorted(dct.items()))] = b
Mutable objects are not hashable because they can be changed in-place, making later key-lookups fail. What would the expected outcome be if you added or removed items from the dictionary you used as the key, for example?
Dictionaries can only use hashable objects as keys, which means they must be immutable. The default dictionary isn't either, so that won't work. You can try a frozendict though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With