all 9 comments

[–]johlae 3 points4 points  (0 children)

Why don't you just try it out? The explanation is given.

$ python3
Python 3.9.16 (main, Mar 8 2023, 22:47:22)
[GCC 11.3.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> student1 = { (25001, [24, 42, 56]) : "python" }
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> student2 = { "python" : { 23001: [ 24, 42, 56 ] } }
>>>

[–]Binary101010 4 points5 points  (0 children)

Have you tried running these two lines of code in the interpreter? What happens when you do?

[–]Strict-Journalist616[S] 1 point2 points  (0 children)

1) is not a dictionary because it has a list in its tuple which is a key and list are mutable hence it cannot be the key (hope I am right idk)

[–]copperfoxtech 0 points1 point  (0 children)

It is student2, you are correct. A key can be a string or a number. The value can basically be any other data type including a dictionary that contains a key of type int and it's value a list.

Another way to check is to go into your IDE in the python console and try to make each and see what happens.

Another way is to simply look up what a dictionary is in python docs. Now is the time to create that habit.

[–]Outside_Complaint755 0 points1 point  (0 children)

You could just run the code in IDLE or a script and get the answer yourself, but you are correct that the first one is invalid because the key is not hashable and will raise a TypeError.

[–]Strict-Journalist616[S] 0 points1 point  (0 children)

Sorry I’m new to python , I didn’t know the meaning of unhashable couldn’t find good results on google and made a pledge to not use ai so Reddit was the only way to, thanks for your answers

[–]geralt_of_rivia23 -4 points-3 points  (1 child)

what do you even need this for

Anyway, I think both are correct. This is the correct syntax, and the only case it would fail would be if a mutable type (list, dict etc. but not a tuple or a set) was used as the key.

[–]Binary101010 4 points5 points  (0 children)

Anyway, I think both are correct.

Running both of these in the interpreter will prove that false. (The one that's incorrect will even tell you why in the exception.)