why below code giving me 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 ----> 1 {i for i in nested_dict.values()}
C:\Users\ABHINA~1\AppData\Local\Temp/ipykernel_12056/1167728052.py in (.0) ----> 1 {i for i in nested_dict.values()}
TypeError: unhashable type: 'dict'
CodePudding user response:
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.
CodePudding user response:
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)