Iterating Over an OrderedDict
00:00
Iterating Over an OrderedDict. Just as with regular dictionaries, you can iterate through an OrderedDict object using several tools and techniques.
00:10
You can iterate over the keys directly, or you can use dictionary methods, such as .items(), .keys(), and .values().
00:27
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.
01:03
Another important feature that OrderedDict has provided since Python 3.5 is that items, keys, and values support reverse iteration using reversed().
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.
01:42
You can use reversed() with the items, keys,
02:02
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 TypeError.
02:31
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 OrderedDict.
Become a Member to join the conversation.
