Dictionary, index and the loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Dictionary, index and the loop

Hi! I don't get one thing in my dict dictionary. When running this: for i in dict: print(dict[i]) it returns all dictionary values. OK. But this one: print(dict[1]) causes an error. Why? The structure dict[] is the same.

1st Mar 2019, 9:24 AM
Artenstall
Artenstall - avatar
1 Answer
+ 6
A dict contains unordered key/value pairs that can't be accessed with an index. In your for loop, you iterate over the keys in the dict and access the items via their key. That's not the same as dict[1] which tries to get the element with the index 1.
1st Mar 2019, 9:43 AM
Anna
Anna - avatar