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

In the diary app video, we use an OrderedDict. Why do we use this, when a normal dictionary works just fine?

I used the orderedDict and also the standard dictionary and it worked just the same.

1 Answer

If you notice that when we use simple dict the order is not the same as we wanted to, as we write it to be.

For example:

We have this dict:

dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Everytime when we running,

for key, value in dict.items():
    print(value)

like i said above, the order is not the same order how is in our code

The order may be: value1, value3, value2 or maybe: value2, value1, value3, etc.

When we use OrderedDict, we can order them how we like them to be ordered

We have this OrderedDict:

ordered_dict = OrderedDict([
    ('key1', 'value1'),
    ('key2', 'value2'),
    ('key3', 'value3')
])

Everytime when we running the foor loop the result always will be: value1, value2, value3. If we change the order in ordereddict, the order that will display will be changed too.

P.S.: Sorry for my bad english, I hope you understand.