How to Convert Between OrderedDict
and dict
in Python
This guide explains how to convert between OrderedDict
(from the collections
module) and regular dict
objects in Python. We'll also cover converting an OrderedDict
to a list. The key difference between a standard dict
and an OrderedDict
is that the OrderedDict
remembers the insertion order of keys, whereas, before Python 3.7, regular dictionaries did not guarantee any particular order. In Python 3.7 and later, standard dict
objects do preserve insertion order.
Converting OrderedDict
to `dict
To convert an OrderedDict
to a standard (unordered in Python < 3.7, ordered in Python >= 3.7) dictionary, simply use the dict()
constructor:
from collections import OrderedDict
ordered_dict = OrderedDict(
[('first', 'tom'),
('last', 'nolan'),
('age', 25)]
)
regular_dict = dict(ordered_dict) # Convert to a regular dict
print(regular_dict)
# Output (Python 3.7+): {'first': 'tom', 'last': 'nolan', 'age': 25}
# Output (Python < 3.7): {'last': 'nolan', 'first': 'tom', 'age': 25} (order *might* be different)
print(type(regular_dict)) # Output: <class 'dict'>
dict(ordered_dict)
: This creates a new dictionary object. The new dictionary will have the same key-value pairs as theOrderedDict
, but it will be a standarddict
.
If the OrderedDict is nested, the recommended way to convert it to dict is to use json.dumps
and json.loads
.
from collections import OrderedDict
import json
ordered_dict = OrderedDict(
[('name', 'tomnolan'),
('address', OrderedDict([('post_code', 123)])),
]
)
json_str = json.dumps(ordered_dict)
regular_dict = json.loads(json_str)
print(regular_dict) # Output: {'name': 'tomnolan', 'address': {'post_code': 123}}
print(type(regular_dict)) # Output: <class 'dict'>
Converting dict
to OrderedDict
To convert a regular dict
to an OrderedDict
, pass the dictionary to the OrderedDict
constructor:
from collections import OrderedDict
my_dict = {
'first': 'tom',
'last': 'nolan',
'age': 25,
}
ordered_dict = OrderedDict(my_dict) # Convert to OrderedDict
print(ordered_dict)
# Output: OrderedDict([('first', 'tom'), ('last', 'nolan'), ('age', 25)])
OrderedDict(my_dict)
: This creates a newOrderedDict
object, preserving the insertion order of the originaldict
(in Python 3.7+).
Converting OrderedDict
to a List
To convert an OrderedDict
to a list, you have several options, depending on what you want in the list:
-
List of keys:
list_of_keys = list(ordered_dict.keys()) # Or simply: list(ordered_dict)
print(list_of_keys) # Output: ['name', 'age', 'topic'] -
List of values:
list_of_values = list(ordered_dict.values())
print(list_of_values) # Output: ['tomnolan', 25, 'Python'] -
List of (key, value) tuples:
list_of_items = list(ordered_dict.items())
print(list_of_items) # Output: [('name', 'tomnolan'), ('age', 25), ('topic', 'Python')]- The
items()
method will return a list of tuples. list_of_items[0]
accesses the tuple element at index 0.list_of_items[0][0]
andlist_of_items[0][1]
access the tuple elements in the list.
- The
When to Use OrderedDict
vs. dict
(Python 3.7+)
- Python 3.7 and later: Standard
dict
objects preserve insertion order. In most cases, you don't needOrderedDict
anymore. Use a regulardict
unless you specifically need the extra features ofOrderedDict
(see below). - Python 3.6 and earlier:
dict
did not guarantee order. If you need to maintain insertion order and are using an older Python version, you must useOrderedDict
. - Explicit Intent: Even in Python 3.7+, using
OrderedDict
can be a way to explicitly communicate to other developers (and your future self) that the order of the items is significant. - Equality Check:
OrderedDict
checks for equality of contents and order, and dict only checks for equality of contents.