Python: OrderedDict vs dict
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:
- Empty dict declaration
2. Add key
, value
to dict.
3. Get values
from dict.
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
Used case:
For example if we have OrderedDict
like in the photo.
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.
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.
- If we need to convert
OrderedDict
to only normal dict very easy. - Just wrap up with
dict()
like this.
If you think it’s useful for you, just clap your hands 👏 to be encouraged me.
GRASSROOT ENGINEER 😘