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 trial

Python Python Collections (2016, retired 2019) Dictionaries Dict Basics

Why 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
Steven Parker
231,269 Points

Dictionaries 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.

Yes, 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?

Because 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.

>>> test_dict = {"a": 1, "b": 2, "a": 3}
>>> test_dict
{'b': 2, 'a': 3}
>>>

You can see that the "a": 1 is dropped and all that you have is the "a": 3

I understand now, thank you.