Reputation: 1
Why below code giving me an error?
nested_dict = {'first':{'a':1},'second':{'b':2}}
{i for i in nested_dict.values()}
error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
C:\Users\ABHINA~1\AppData\Local\Temp/ipykernel_12056/1167728052.py in <module>
----> 1 {i for i in nested_dict.values()}
C:\Users\ABHINA~1\AppData\Local\Temp/ipykernel_12056/1167728052.py in <setcomp>(.0)
----> 1 {i for i in nested_dict.values()}
TypeError: unhashable type: 'dict'
Upvotes: 0
Views: 39
Reputation: 20450
You are confused about notation.
Consider these two examples:
>>> {i for i in [('a', 1), ('b', 2)]}
{('a', 1), ('b', 2)}
>>>
>>> {k: v for k, v in [('a', 1), ('b', 2)]}
{'a': 1, 'b': 2}
Using single variable i
is asking for a set
result.
Each element of a set must be hashable, typically immutable, like tuple, str or int.
Using the key: value notation OTOH would be asking for a dict
result.
Upvotes: 1
Reputation: 1539
Hi actually i tried this and it works:
nested_dict = {'first':{'a':1},'second':{'b':2}}
for i in nested_dict:
for j in nested_dict[i]:
print(j)
and also this works too :
nested_dict = {'first':{'a':1},'second':{'b':2}}
for i in nested_dict.values():
print(i)
Upvotes: 0