Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialleonardbode
Courses Plus Student 4,011 PointsWhy does test_dict["a"] return 3 if test_dict = {"a": 1, "b": 2, "a": 3} I thought dictionaries were not ordered?
Found in Python Collections course quiz.
1 Answer
Steven Parker
231,236 PointsDictionaries are not ordered, but they can be indexed using their keys.
So for example, you could not predict what the "third" item might be in a dictionary. But you can always get the value associated with a particular key (such as "a" in your example above).
This example is unusual since it shows the same key being assigned twice. But since dictionary keys are required to be unique, the value for "a" is simply replaced with 3 instead of creating a new key/value pair.
leonardbode
Courses Plus Student 4,011 Pointsleonardbode
Courses Plus Student 4,011 PointsYes, I understand that. However, I don't understand the logic behind test_dict["a"] always returning 3 and never 1?
Edit: Why is the value of "a" replaced with 3?
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsBecause that was the last value assigned to the key 'a'. If there are duplicate keys, then the last value assigned to that key is the one that gets used.
Try printing out your dictionary after you create it.
You can see that the
"a": 1
is dropped and all that you have is the"a": 3
leonardbode
Courses Plus Student 4,011 Pointsleonardbode
Courses Plus Student 4,011 PointsI understand now, thank you.