Iterating Over an OrderedDict
Iterating Over an
OrderedDict. Just as with regular dictionaries, you can iterate through an
OrderedDict object using several tools and techniques.
You can iterate over the keys directly, or you can use dictionary methods, such as
This loop iterates over the keys of
numbers directly. This loop iterates over items, this loop iterates over keys, and this loop iterates over values.
Another important feature that
OrderedDict has provided since Python 3.5 is that items, keys, and values support reverse iteration using
01:13 This feature was added to regular dictionaries in Python 3.8, so if your code uses it, then your backwards compatibility is much more restricted with normal dictionaries.
You can use
reversed() with the items, keys,
and values of an
OrderedDict object. Regular dictionaries also support reverse iteration. However, if you try to use
reversed() with a regular dictionary object in a Python version lower than 3.8, then you get a
If you need to iterate over the items in a dictionary in reverse order, then
OrderedDict is a good ally. Using a regular dictionary dramatically reduces your backwards compatibility because reverse iteration wasn’t added to regular dictionaries until Python 3.8. In the next section of the course, you’ll take a look at some of the unique features of
Become a Member to join the conversation.