Python: OrderedDict vs dict

Grassroot Engineer
3 min readNov 19, 2022

--

Yeb…it’s similar to Dictionary in real life because it has key and value.

I think most of Pythonista have known well for dict, it looks like this or can see more about dict details => here.

car = {
'brand': 'Honda',
'model': 'city',
'color': 'black',
'year': 2012
}

But if some day you have to use Django framework, you will see type OrderedDict as well, what is it?

Since Python 3.6 will have OrderedDict, actuatlly it’s the same as dict but basically OrderedDict is dictionary that have been orderred, so we can ensure that order of items is important.

Comparing dict and OrderedDict:

  1. Empty dict declaration
ประกาศ Empty dict

2. Add key, value to dict.

Add key, value to dict will do the same.

3. Get values from dict.

Recomment to use get() to prevenet program error in case of wrong spelling in key.

4. Any methods in dict also can use the same.

car = {
'brand': 'Honda',
'model': 'city',
'color': 'black',
'year': 2012
}

for key, value in car.items(): # Because .items() return 2 elements.
print(key, val


# output
# -----------
# brand Honda
# model city
# color black
# year 2012

5. In case we need to sort dict or OrderedDict

  • Sorting by key
  • Sorting by value
sort by key and value

Used case:

For example if we have OrderedDict like in the photo.

OrderedDict vs dict

Both of them are nested dict so if we get value name_eng from dict will need to get like this.

data_ordered_dict.get('semester_courses').get('course').get('name_eng')


# output
# Information Technology Fundamentals

But the problem is if value in any layers is None so program will broke like this.

Program broke if value of dict is None, in case of nested dict.

So I recommend to use this function to get value of dict in case of nested dict.

from functools import reduce


def deep_get(dictionary, keys, default=None):
return reduce(
lambda d, key: d.get(key, default) if isinstance(
d, dict) else default, keys.split('.'), dictionary
)

The result will be correct and program not broke.

Important !!! Solution for solving getting value from nested dict.
  • If we need to convert OrderedDict to only normal dict very easy.
  • Just wrap up with dict() like this.
convert OrderedDict to dict()

If you think it’s useful for you, just clap your hands 👏 to be encouraged me.

GRASSROOT ENGINEER 😘

--

--