Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "unhashable type: 'set'" when building a dictionary?

Tags:

python-2.7

I'm fairly new to Python, trying to build a dictionary of keys and values where the values are dictionaries with keys and values. The idea, if a value is in the list of values, return the key. I have working code but it breaks when I try to add the second dictionary.

This works:

lookup = {
    3: ("TRUE", ["t", "true", "1", "yes"]),
    4: ("FALSE", ["f", "false", "0", "no"])
     }

This doesn't work:

lookup = {
    3: {{"TRUE", {"t", "true", "1", "yes"}}, {"FALSE", {"f", "fake", "farce", "fallacy", "falsehood"}}},
    4: {{"FALSE", {"f", "false", "0", "no"}}}
}

What am I doing wrong and how do I fix it?

like image 951
DenaliHardtail Avatar asked Jan 23 '26 19:01

DenaliHardtail


1 Answers

You cannot use a set which is what {"t", "true", "1", "yes"} etc.. are, if you want a dict of dicts where keys have multiple values use a list, tuple or indeed a set to store the values but you cannot use sets as keys because they are not hashable, you also need to create key pairings:

lookup = {
    3:{"TRUE": ["t", "true", "1", "yes"], "FALSE":["f", "fake", "farce", "fallacy", "falsehood"]},
    4: {"FALSE": ["f", "false", "0", "no"]}}

sets can be created using set([1,2,3]) or {1,2,3}, the latter does resemble a dict, what is different in the dict syntax is the key/value pairings i.e {1:[1,2]}

Just to see the different ways to use the set syntax have a look at creating the same dict where the multiple values are stored in sets:

lookup = {
    3:{"TRUE": {"t", "true", "1", "yes"}, "FALSE":{"f", "fake", "farce", "fallacy", "falsehood"}},
    4: {"FALSE": set(["f", "false", "0", "no"])}}

To access the elements:

In [17]: lookup[3]["TRUE"]
Out[17]: {'1', 't', 'true', 'yes'}

In [18]: lookup[3]["FALSE"]
Out[18]: {'f', 'fake', 'fallacy', 'falsehood', 'farce'}

In your original dict you have the keys, 3,4 and then the values for each key stored in a tuple containing two items a string and a list of strings:

("TRUE", ["t", "true", "1", "yes"])
like image 96
Padraic Cunningham Avatar answered Jan 27 '26 00:01

Padraic Cunningham



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!