コンテンツにスキップ

OrderedDictの使い方: Pythonで簡単に辞書を順序通りに使う方法は?

[

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


Choosing Between OrderedDict and dict

In the Python community, there has been a debate about whether to use OrderedDict or the built-in dict class when you need a dictionary that remembers the order of its items. Starting from Python 3.6, the dict class now preserves the order of its items, which was previously a feature exclusive to OrderedDict. In this tutorial, we will explore the differences between OrderedDict and dict and help you make an informed decision about which one to use.

Getting Started With Python’s OrderedDict

Creating OrderedDict Objects

To create an OrderedDict object, you can simply import it from the collections module:

from collections import OrderedDict
ordered_dict = OrderedDict()

Managing Items in an OrderedDict

To add items to an OrderedDict, you can use the update() method or directly assign values to keys:

ordered_dict.update({'a': 1, 'b': 2, 'c': 3})
ordered_dict['d'] = 4

You can also remove items from an OrderedDict using the del keyword or the pop() method:

del ordered_dict['d']
ordered_dict.pop('c')

Iterating Over an OrderedDict

When you iterate over an OrderedDict, the items will be returned in the order they were inserted:

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

Iterating in Reversed Order With reversed()

If you want to iterate over an OrderedDict in reversed order, you can use the reversed() function:

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

Exploring Unique Features of Python’s OrderedDict

Reordering Items With .move_to_end()

One unique feature of OrderedDict is the ability to move an item to the end of the dictionary:

ordered_dict.move_to_end('b')

Removing Items With .popitem()

You can remove and return the last item from an OrderedDict using the popitem() method:

key, value = ordered_dict.popitem()

Testing for Equality Between Dictionaries

When comparing two dictionaries for equality, OrderedDict takes into account both the key-value pairs and the order of insertion:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 2, 'a': 1}
ordered_dict1 = OrderedDict(dict1)
ordered_dict2 = OrderedDict(dict2)
print(dict1 == dict2) # True
print(ordered_dict1 == ordered_dict2) # False

Appending New Attributes to a Dictionary Instance

With OrderedDict, you can add new attributes to the dictionary instance without affecting the order of the existing items:

ordered_dict.new_attribute = 'value'

Merging and Updating Dictionaries With Operators

Both OrderedDict and dict can be merged or updated using the | and |= operators:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = dict1 | dict2
dict1 |= dict2

Considering Performance

In terms of performance, dict is generally faster than OrderedDict due to its simpler implementation. However, the difference is usually negligible unless you are working with large datasets.

Selecting the Right Dictionary for the Job

When choosing between OrderedDict and dict, consider the following:

  • If insertion order is important and you need to preserve it, use OrderedDict.
  • If order doesn’t matter and you want to optimize performance, use dict.

Building a Dictionary-Based Queue

As an example of using OrderedDict, let’s build a dictionary-based queue:

class Queue:
def __init__(self):
self.queue = OrderedDict()
def push(self, item):
self.queue[item] = None
def pop(self):
return self.queue.popitem(last=False)[0]
def size(self):
return len(self.queue)

Conclusion

In this tutorial, you have learned about the differences between OrderedDict and dict in Python. While the built-in dict class now preserves the order of its items starting from Python 3.6, OrderedDict still provides some unique features. Consider your specific needs when choosing between the two and remember that performance differences are usually negligible.