Convert OrderedDict to regular Dict or List in Python

avatar
Borislav Hadzhiev

Last updated: Feb 23, 2023
5 min

banner

# Table of Contents

  1. Convert an OrderedDict to a regular Dict in Python
  2. Convert a dict to an OrderedDict in Python
  3. Convert an OrderedDict to a List in Python

# Convert an OrderedDict to a regular Dict in Python

Use the dict() class to convert an OrderedDict to a regular dict, e.g. dictionary = dict(ordered_dict).

The dict() class can be passed an iterable of key-value pairs and returns a new dictionary.

main.py
from collections import OrderedDict import json # โœ… Convert an OrderedDict to a regular Dict ordered_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) dictionary = dict(ordered_dict) # ๐Ÿ‘‡๏ธ {'first': 'bobby', 'last': 'hadz', 'age': 30} print(dictionary) print(type(dictionary)) # ๐Ÿ‘‰๏ธ <class 'dict'> # --------------------------------------------------- # โœ… Convert a nested OrderedDict to a regular dict ordered_dict = OrderedDict( [('name', 'bobbyhadz'), ('address', OrderedDict([('post_code', 123)])), ] ) json_str = json.dumps(ordered_dict) regular_dict = json.loads(json_str) # ๐Ÿ‘‡๏ธ {'name': 'bobbyhadz', 'address': {'post_code': 123}} print(regular_dict) print(type(regular_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

convert an ordered dict to regular dict

The first example uses the dict() class to convert an OrderedDict object to a dict.

You can directly pass the OrderedDict to the dict() class if it isn't a nested OrderedDict object.
main.py
from collections import OrderedDict ordered_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) dictionary = dict(ordered_dict) # ๐Ÿ‘‡๏ธ {'first': 'bobby', 'last': 'hadz', 'age': 30} print(dictionary) print(type(dictionary)) # ๐Ÿ‘‰๏ธ <class 'dict'> print(dictionary['first']) # ๐Ÿ‘‰๏ธ bobby print(dictionary['last']) # ๐Ÿ‘‰๏ธ hadz

The dict() class can be passed an iterable of keyword arguments or an iterable of key-value pairs and returns a new dictionary.

If you have a nested OrderedDict object, use the json module instead.

# Convert a nested OrderedDict to a regular Dict in Python

To convert a nested OrderedDict to a regular dict:

  1. Use the json.dumps() method to convert the nested OrderedDict to a JSON string.
  2. Use the json.loads() method to convert the JSON string to a native Python dictionary.
main.py
from collections import OrderedDict import json ordered_dict = OrderedDict( [('name', 'bobbyhadz'), ('address', OrderedDict([('post_code', 123)])), ] ) json_str = json.dumps(ordered_dict) regular_dict = json.loads(json_str) # ๐Ÿ‘‡๏ธ {'name': 'bobbyhadz', 'address': {'post_code': 123}} print(regular_dict) print(type(regular_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

convert nested ordered dict to regular dict

The first step is to use the json.dumps() method to convert the nested OrderedDict object to a JSON string.

main.py
from collections import OrderedDict import json ordered_dict = OrderedDict( [('name', 'bobbyhadz'), ('address', OrderedDict([('post_code', 123)])), ] ) json_str = json.dumps(ordered_dict) print(json_str) # ๐Ÿ‘‰๏ธ {"name": "bobbyhadz", "address": {"post_code": 123}} print(type(json_str)) # ๐Ÿ‘‰๏ธ <class 'str'>

The json.dumps method converts a Python object to a JSON formatted string.

The last step is to use the json.loads() method to parse the JSON string into a native Python dict.
main.py
from collections import OrderedDict import json ordered_dict = OrderedDict( [('name', 'bobbyhadz'), ('address', OrderedDict([('post_code', 123)])), ] ) json_str = json.dumps(ordered_dict) regular_dict = json.loads(json_str) # ๐Ÿ‘‡๏ธ {'name': 'bobbyhadz', 'address': {'post_code': 123}} print(regular_dict) print(type(regular_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

The json.loads method parses a JSON string into a native Python object.

We can't directly pass a nested OrderedDict to the dict() class because the dict() class expects an iterable of keyword arguments or an iterable of key-value pairs.

main.py
my_dict = dict( [('id', 1), ('first', 'bobby'), ('last', 'hadz')] ) print(my_dict) # ๐Ÿ‘‰๏ธ {'id': 1, 'first': 'bobby', 'last': 'hadz'}

The OrderedDict class is a subclass of dict that remembers the order in which its entries were added.

Note that as of Python 3.7, the standard dict class is guaranteed to preserve the insertion order as well.

# Convert a dict to an OrderedDict in Python

To convert a dict to an OrderedDict:

  1. Pass the dict object to the OrderedDict class if you use a Python version of 3.7+.
  2. Use a list comprehension to construct an ordered list of key-value pairs if you use a Python version older than 3.7.
main.py
from collections import OrderedDict my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30, } # โœ… Convert dict to OrderedDict (Python version older than 3.7) ordered_keys = ['first', 'last', 'age'] ordered_dict = OrderedDict( [(key, my_dict[key]) for key in my_dict] ) # ๐Ÿ‘‡๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(ordered_dict) # ------------------------------------------------ # โœ… Convert dict to OrderedDict (Python version 3.7 +) ordered_dict = OrderedDict(my_dict) # ๐Ÿ‘‡๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(ordered_dict)

convert dict to ordered dict

In the first example, we ordered the keys of the dict in a list.

The OrderedDict class is a subclass of dict that remembers the order in which its entries were added.

As of Python 3.7, the standard dict class is guaranteed to preserve the insertion order as well.

However, in versions older than 3.7, the insertion order of dict objects is not preserved.

We used a list comprehension to iterate over the ordered list of keys.

main.py
from collections import OrderedDict my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30, } ordered_keys = ['first', 'last', 'age'] list_of_tuples = [(key, my_dict[key]) for key in my_dict] # ๐Ÿ‘‡๏ธ [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] print(list_of_tuples) ordered_dict = OrderedDict(list_of_tuples) # ๐Ÿ‘‡๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(ordered_dict)
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we return a tuple containing the current key and the corresponding value.

The insertion order for OrderedDict objects is preserved, so the last step is to pass the list of key-value pairs to the OrderedDict class.

# Directly passing the dict object to the OrderedDict class

If you use a version of Python greater than 3.7, you can directly pass the dict object to the OrderedDict class as the insertion order for dict objects is preserved.

main.py
from collections import OrderedDict my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30, } ordered_dict = OrderedDict(my_dict) # ๐Ÿ‘‡๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(ordered_dict)

Passing the dictionary to the OrderedDict class works even if the dictionary is nested.

main.py
from collections import OrderedDict my_dict = { 'first': 'bobby', 'last': 'hadz', 'address': { 'post_code': 123 } } ordered_dict = OrderedDict(my_dict) # ๐Ÿ‘‡๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('address', {'post_code': 123})]) print(ordered_dict)

# Convert an OrderedDict to a List in Python

To convert an OrderedDict to a list:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use the list() class to convert the view object to a list.
main.py
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) list_of_items = list(my_dict.items()) # ๐Ÿ‘‡๏ธ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(list_of_items) list_of_keys = list(my_dict.keys()) print(list_of_keys) # ๐Ÿ‘‰๏ธ ['name', 'age', 'topic'] list_of_values = list(my_dict.values()) print(list_of_values) # ๐Ÿ‘‰๏ธ ['bobbyhadz', 30, 'Python']

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

Make sure to pass the view object to the list() class to convert the view object to a list.
main.py
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) list_of_items = list(my_dict.items()) # ๐Ÿ‘‡๏ธ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(list_of_items) print(list_of_items[0]) # ๐Ÿ‘‰๏ธ ('name', 'bobbyhadz') print(list_of_items[0][0]) # ๐Ÿ‘‰๏ธ name print(list_of_items[0][1]) # ๐Ÿ‘‰๏ธ bobbyhadz

You can use the dict.keys() method if you need to get a view object of the keys of the OrderedDict.

main.py
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) list_of_keys = list(my_dict.keys()) print(list_of_keys) # ๐Ÿ‘‰๏ธ ['name', 'age', 'topic'] print(list_of_keys[0]) # ๐Ÿ‘‰๏ธ name print(list_of_keys[1]) # ๐Ÿ‘‰๏ธ age

The dict.keys method returns a new view of the dictionary's keys.

Make sure to convert the view object to a list before accessing it at a specific index.

There is also a dict.values() method if you need to get a view object of the values of the OrderedDict.

main.py
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) list_of_values = list(my_dict.values()) print(list_of_values) # ๐Ÿ‘‰๏ธ ['bobbyhadz', 30, 'Python'] print(list_of_values[0]) # ๐Ÿ‘‰๏ธ bobbyhadz print(list_of_values[1]) # ๐Ÿ‘‰๏ธ 30

The dict.values method returns a new view of the dictionary's values.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev