콘텐츠로 건너뛰기

파이썬 ordereddict 사용법

[

OrderedDict vs dict in Python: The Right Tool for the Job

Sometimes you need a Python dictionary that remembers the order of its items. In the past, you had only one tool for solving this specific problem: Python’s OrderedDict. It’s a dictionary subclass specially designed to remember the order of items, which is defined by the insertion order of keys.

This changed in Python 3.6. The built-in dict class now keeps its items ordered as well. Because of that, many in the Python community now wonder if OrderedDict is still useful. A closer look at OrderedDict will uncover that this class still provides valuable features.

In this tutorial, you ‘ll learn how to:

  • Create and use OrderedDict objects in your code
  • Identify the differences between OrderedDict and dict
  • Understand the pros and cons of using OrderedDict vs dict

With this knowledge, you’ll able to choose the dictionary class that best fits your needs when you want to preserve the order of items.

By the end of the tutorial, you’ll see an example of implementing a dictionary-based queue using OrderedDict, which would be more challenging if you used a regular dict object.

Choosing Between OrderedDict and dict

For years, Python dictionaries were unordered data structures. Python developers were used to this fact, and they relied on lists or other sequences when they needed to keep their data in order. With time, developers found a need for a new type of dictionary, one that would keep its items ordered.

Back in 2008, PEP 372 introduced the idea of adding a new dictionary class to collections. Its main goal was to remember the order of items as defined by the order in which keys were inserted. That was the origin of OrderedDict.

Core Python developers wanted to fill in the gap and provide a dictionary that could preserve the order of inserted keys. That, in turn, allowed for a more straightforward implementation.

Getting Started With Python’s OrderedDict

Now that you have a brief background on why OrderedDict was created, let’s dive into using it.

Creating OrderedDict Objects

To create an OrderedDict object, you can use the following syntax:

from collections import OrderedDict
ordered_dict = OrderedDict()

OrderedDict provides the same functionality as a regular dict. You can add and update key-value pairs, access values by keys, and perform other dictionary operations.

Managing Items in an OrderedDict

The OrderedDict class provides additional methods to manage items in the dictionary. Here are some examples:

  • ordered_dict[key] = value: This is the same as adding or updating a key-value pair in a regular dictionary.
  • ordered_dict.popitem(last=True): This method removes and returns the last inserted key-value pair if last=True. If last=False, it removes and returns the first inserted key-value pair.
  • ordered_dict.move_to_end(key, last=True): Moves the specified key to the end if last=True, or to the beginning if last=False. This allows you to change the order of items in the dictionary.

Iterating Over an OrderedDict

One advantage of OrderedDict is that it preserves the order of items during iteration. When you iterate over an OrderedDict, you’ll get the items in the same order they were inserted.

Here’s an example:

for key, value in ordered_dict.items():
print(key, value)

This code will print the key-value pairs in the order they were added.

Iterating in Reversed Order With reversed()

In addition to preserving the insertion order, OrderedDict allows you to iterate over its items in reversed order. The reversed() function can be used to achieve this.

Here’s an example:

for key, value in reversed(ordered_dict.items()):
print(key, value)

This code will print the key-value pairs in reversed order.

Exploring Unique Features of Python’s OrderedDict

OrderedDict provides some unique features that are not available in regular dictionaries. Let’s take a look at some of these features.

Reordering Items With .move_to_end()

As mentioned earlier, the move_to_end() method allows you to change the order of items in the OrderedDict. This can be useful when you want to move a specific item to the beginning or end of the dictionary.

Here’s an example:

# Move a specific key to the end
ordered_dict.move_to_end('key')
# Move a specific key to the beginning
ordered_dict.move_to_end('key', last=False)

Removing Items With .popitem()

The popitem() method not only removes but also returns the key-value pair. By default, it removes and returns the last inserted item. However, you can specify last=False to remove and return the first inserted item.

Here’s an example:

# Remove and return the last inserted item
last_item = ordered_dict.popitem()
# Remove and return the first inserted item
first_item = ordered_dict.popitem(last=False)

Testing for Equality Between Dictionaries

OrderedDict also provides a way to test for equality between dictionaries. When you compare two OrderedDict objects, the order of items is also taken into account.

Here’s an example:

dict1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
dict2 = OrderedDict([('a', 1), ('c', 3), ('b', 2)])
print(dict1 == dict2) # False

In this example, even though the key-value pairs are the same, the dictionaries are not considered equal because the order of items is different.

Appending New Attributes to a Dictionary Instance

With OrderedDict, you can also add attributes to a dictionary instance. This can be useful when you want to store additional information about the dictionary.

Here’s an example:

ordered_dict.new_attribute = 'new_value'

Now, new_attribute is added as an attribute to the OrderedDict instance.

Merging and Updating Dictionaries With Operators

Python’s dict class provides the update() method to merge or update dictionaries. The same method can be used with OrderedDict to achieve the same result.

Here’s an example:

dict1 = OrderedDict([('a', 1), ('b', 2)])
dict2 = OrderedDict([('c', 3), ('d', 4)])
# Merge dict2 into dict1
dict1.update(dict2)
print(dict1)

The output will be: OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

Considering Performance

When it comes to performance, OrderedDict is slightly slower than dict due to the additional overhead of keeping track of the order of items. However, the difference is usually negligible unless you’re working with a large number of items.

If performance is a critical factor in your application, and you don’t need to preserve the order of items, it’s recommended to use a regular dict.

Selecting the Right Dictionary for the Job

In most cases, using a regular dict will be sufficient for your needs. However, if you specifically need to preserve the order of items, or if you require the unique features provided by OrderedDict, then OrderedDict is the right choice.

Consider the requirements of your application and decide whether you need the additional functionality and trade-off in performance that OrderedDict offers.

Building a Dictionary-Based Queue

To showcase the usefulness of OrderedDict, let’s create an example of a dictionary-based queue. In a regular dictionary, the order of items is not preserved, so implementing a queue can be challenging.

Using OrderedDict, you can easily create a queue by adding items to the end and removing items from the beginning.

Here’s an example:

from collections import OrderedDict
queue = OrderedDict()
# Adding items to the queue
queue['item1'] = 1
queue['item2'] = 2
queue['item3'] = 3
# Removing items from the queue
item = queue.popitem(last=False)
print(item) # ('item1', 1)

In this example, the items are added to the end of the dictionary, and when an item is removed, it is taken from the beginning.

This is a simple implementation of a queue using OrderedDict. Without OrderedDict, achieving the same functionality would require additional data structures or custom implementation.

Conclusion

In conclusion, OrderedDict is a valuable tool when you need to preserve the order of items in a dictionary. While regular dictionaries now maintain the order as well, OrderedDict offers additional features and flexibility.

By understanding the differences and trade-offs between OrderedDict and dict, you can choose the dictionary class that best suits your needs. Keep in mind the requirements of your application and consider the potential impact on performance.

In most cases, a regular dict will suffice. However, when order and additional functionality are crucial, OrderedDict is the right choice.