Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a dictionary as key for a dictionary in Python

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

like image 984
Pat Avatar asked Dec 02 '25 09:12

Pat


2 Answers

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?

like image 186
Martijn Pieters Avatar answered Dec 04 '25 01:12

Martijn Pieters


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.

like image 21
orlp Avatar answered Dec 04 '25 00:12

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!