简体   繁体   中英

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

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.

Python wiki :

To be used as a dictionary key, an object must support the hash function (eg through __hash__), equality comparison (eg through __eq__ or __cmp__), and must satisfy the correctness condition above.

So trying this out:

a = {0: 0}
hash(a)

yields the error:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    hash(a)
TypeError: unhashable type: 'dict'

basically just confirming what mgilson already said. You are out of luck as far as using a dictionary (or a list, etc) as a dictionary key.

a dict can't be used as a key as it is unhashable.

hash(a)

so i would rethink your problem or if you really need to hash a dict you could represent is aa string , or tuples and hash by that:

hash(tuple(dict.items()))
hash(''.join(["%s%s" %(k, v) for k,v in dict.items()]))

Thanks to all who replied. I know this was a fairly basic question and all the infos on hashability and mutability is much appreciated.

I will indeed pursue the approach of mapping an input vector (a dictionary itself) to the sorted tuple of its items. This characterises a given dictionary unambiguously and is a hashable data structure such that it can be used as a dictionary key.

def get_key( dict1, dict2 ):

    list = dict1.items() + dict2.items()
    list.sort()
    return tuple( list )

a,b = {'feature1':0}, {'feature1':1}
print get_key( a, b )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM