-1

Suppose I have two dictionaries as such dict1 and dict2 and I wish to compare the keys of both dictionaries and if both are the same, plan on switching the value of the second dictionary to the key of the first dictionary. I came up with the following code:

dict1 = {"1|1":["xyx","zzz","zxz"],"1|2":["aa","xaa","bli"],"1|3":["jjj","kkk"]}

dict2 = {"1|1":{"hum1":"hum2"},"1|2":{"hum3":"hum4"},"1|4":{"hum5"}}

new_dict = {}

for k,v in dict1.items():
    for m,n in dict2.items():
        if(k==m):
            #new_dict[n] = v
            new_dict.update({n: v})
        
        
print(new_dict)




##new_dict = {{"hum1":"hum2"}:["xyx","zzz","zxz"],{"hum3":"hum4"}:["aa","xaa","bli"]}   expected output 

I stumble upon the error: unhashable type: 'dict'

What might I be doing wrong here?

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
  • Your `new_dict` isn't valid Python, a dictionary like `{"hum1": "hum2"}` cannot be a dictionary key. – jonrsharpe Nov 18 '20 at 15:11
  • So , is there any alternative ? – Manjunath R Nov 18 '20 at 15:13
  • You are using a value as a key. That value is a non-hashable type (as the error message says) which is okay for a value, but not for a key. – Kenny Ostrom Nov 18 '20 at 15:13
  • Does this answer your question? [What does "hashable" mean in Python?](https://stackoverflow.com/questions/14535730/what-does-hashable-mean-in-python) – loonatick Nov 18 '20 at 15:13
  • 2
    It's not clear to me what you're trying to achieve, so I don't know. Maybe a *tuple* `("hum1", "hum2")` as a key? How would you *use* the dictionary you're creating? – jonrsharpe Nov 18 '20 at 15:13
  • This sounds like an x-y problem. You literally can't do it like you said, but what did you actually want? Do you want to look up "hum1" and find ["xyx","zzz","zxz"]? What about hum2? Or is it more of a nested dict thing new_dict["hum1"]["hum2"] = ["xyx","zzz","zxz"] ? We can't tell what was intended. – Kenny Ostrom Nov 18 '20 at 15:48

2 Answers2

0

You are using a dict as a key, which is unhashable, You might use a Tuple, and here's compact version with zip() and dict comprehension:

new_list = {tuple(dict2[m].items()):dict1[k] for k,m in zip(dict1,dict2) if k==m}
programmer365
  • 12,641
  • 3
  • 7
  • 28
0

The idea behind the dictionary is that the keys are hashable , meaning we apply some calculus to convert each key into a unique value. For that purpose, the key has to be immutable.

  • Hashable: string, int, float, tuple, bool.
  • Unhashable: dict, list, set.

You need to use a hashable type as key, for which you could transform n in new_dict.update({n: v}).

For example using: str(n) instead of n

MrJavy
  • 186
  • 6