Python中的有序字典(OrderedDict)

Python的OrderedDict是一个字典子类,它会保持项目插入的顺序。当我们遍历OrderedDict时,项目会按照它们被插入的顺序返回。普通字典不会追踪插入顺序。因此,在对其进行迭代时,项目会按照任意的顺序返回。当我们想要确保项目按照插入的顺序返回时,我们可以使用OrderedDict。

Python有序字典

  • OrderedDict is part of python collections module.
  • We can create an empty OrderedDict and add items to it. If we create an OrderedDict by passing a dict argument, then the ordering may be lost because dict doesn’t maintain the insertion order.
  • If an item is overwritten in the OrderedDict, it’s position is maintained.
  • If an item is deleted and added again, then it moves to the last.
  • OrderedDict popitem removes the items in FIFO order. It accepts a boolean argument last, if it’s set to True then items are returned in LIFO order.
  • We can move an item to the beginning or end of the OrderedDict using move_to_end function. It accepts a boolean argument last, if it’s set to False then item is moved to the start of the ordered dict.
  • From python 3.6 onwards, order is retained for keyword arguments passed to the OrderedDict constructor, refer PEP-468.
  • We can use reversed() function with OrderedDict to iterate elements in the reverse order.
  • Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()).
  • Equality tests between OrderedDict and other Mapping objects are order-insensitive like regular dictionaries. This allows OrderedDict objects to be substituted anywhere a regular dictionary is used.

Python有序字典示例

让我们看一些Python OrderedDict的代码示例。

创建有序字典对象

from collections import OrderedDict

# creating a simple dict
my_dict = {'kiwi': 4, 'apple': 5, 'cat': 3}

# creating empty ordered dict
ordered_dict = OrderedDict()
print(ordered_dict)

# creating ordered dict from dict
ordered_dict = OrderedDict(my_dict)
print(ordered_dict)

结果:

OrderedDict()
OrderedDict([('kiwi', 4), ('apple', 5), ('cat', 3)])

在有序字典(OrderedDict)中添加、替换、移除项目。

# adding elements to dict
ordered_dict['dog'] = 3

# replacing a dict key value
ordered_dict['kiwi'] = 10
print(ordered_dict)

# removing and adding a value
ordered_dict.pop('kiwi')
print(ordered_dict)
ordered_dict['kiwi'] = 4
print(ordered_dict)

输出:

OrderedDict([('kiwi', 10), ('apple', 5), ('cat', 3), ('dog', 3)])
OrderedDict([('apple', 5), ('cat', 3), ('dog', 3)])
OrderedDict([('apple', 5), ('cat', 3), ('dog', 3), ('kiwi', 4)])

有序字典 move_to_end 示例

# moving apple to end and dog to start
ordered_dict.move_to_end('apple')
ordered_dict.move_to_end('dog', False)
print(ordered_dict)

输出:

OrderedDict([('dog', 3), ('cat', 3), ('kiwi', 4), ('apple', 5)])

有序字典popitem示例

# pop last item
item = ordered_dict.popitem(True)
print(item)
print(ordered_dict)

输出:产出/产量

('apple', 5)
OrderedDict([('dog', 3), ('cat', 3), ('kiwi', 4)])

有序字典的逆向迭代

# reversed iteration
for item in reversed(ordered_dict):
    print(item)

产出:输出

kiwi
cat
dog

有序字典的相等性测试示例

# equality tests
d1 = {'a': 'A', 'b': 'B'}
d2 = {'b': 'B', 'a': 'A'}

od1 = OrderedDict({'a': 'A', 'b': 'B'})
od2 = OrderedDict({'b': 'B', 'a': 'A'})

print(d1 == d2)
print(od1 == od2)
print(d1 == od1)

输出:

True
False
True

你可以从我们的GitHub代码库中下载完整的示例代码。

参考资料:Python文档

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds