Python字典的选择之道:掌握六种类型的终极指南!( 二 )


下面是代码片段 。
from collections import OrderedDicta = OrderedDict({'one': 1, 'two': 2, 'three': 3, 'four': 4})print(a)# output: OrderedDict([('one', 1) ,  ('two', 2)])a.move_to_end('one', last=True) # 将'one'移至末尾print(a)# output: OrderedDict([('two', 2), ('three', 3), ('four', 4), ('one', 1)])a.move_to_end('three', last=False) # 将'three'移到开头print(a)# output: OrderedDict([('three', 3), ('two', 2),('four', 4),('one', 1)])3.4 collections.ChainMap另一种Python字典类型是collections.ChainMap,Python的ChainMap是一种类似字典的类,可以将多个字典合并为一个视图 。这种类型的字典允许开发者在多个字典中搜索一个键,就好像它们都合并成了一个单一的字典 。

Python字典的选择之道:掌握六种类型的终极指南!

文章插图
使用Python ChainMap的示例
下面是代码片段 。
from collections import ChainMapa = {'one': 1, 'two': 2}b = {'three': 3, 'four': 4}c = {'five': 5, 'six': 6, 'three': 3.1}merged = ChainMap(a, b,c)print(merged)# output: ChainMap({'one': 1,'two': 2},{'three': 3, 'four': 4},{'five': 5, 'six': 6, 'three': 3.1})print(merged['three']) # 只返回关键字的第一次出现结果# output:3请注意,ChainMap只会返回要搜索的键的第一次出现 。另外还要记?。?ChainMap只存储对实际对象的引用;因此,如果在任何一个原始字典中进行了更改,ChainMap也会随之更新 。
Python字典的选择之道:掌握六种类型的终极指南!

文章插图
使用Python ChainMap的示例
下面是代码片段 。
from collections import ChainMapa = {'one': 1, 'two': 2}b = {'three': 3, 'four': 4}c = {'five': 5, 'six': 6, 'three': 3.1}merged = ChainMap(a, b, c )a['one'] = 1.1print(merged['one'])# output: 1.13.5 collections.CounterCounter是Python中另一个能够计数可散列对象的字典 。Python开发者通常使用collections.Counter来计算可迭代对象中元素的频率;例如,可以使用这种类型的Python字典来计算句子中使用的单词数量 。
Python字典的选择之道:掌握六种类型的终极指南!

文章插图
使用Python Counter的示例
下面是代码片段 。
from collections import Countersentence = "we can't control our thoughts, but we can control our words"a = Counter(sentence.split(' '))print(a)# output: Counter({'we': 2, 'control': 2, 'our': 2,"can't": 1, 'thoughts': 1,'but': 1, 'can': 1, 'words': 1})print(a.most_common(2)) # 获得2个出现次数最多的元素# output: [('we', 2),('control', 2)]如果需要列出出现频率最高的n个元素及其计数,从最常见到最不常见,可以在Counter对象上使用most_common函数 。如果n为None,它将列出所有元素的计数 。
3.6 collections.UserDict本文要讨论的最后一种Python字典类型是UserDict字典 。UserDict也是collections模块提供的一个类 。这个类设计成用作创建自定义字典类对象的基类 。
当需要定义自己的类似字典的数据结构时,可以使用collections.UserDict 。想象一个简单的场景,需要将每个值乘以5并保存在自定义的Python字典中 。通过使用UserDict , 可以像这样实现:
Python字典的选择之道:掌握六种类型的终极指南!

文章插图
使用Python UserDict的示例
下面是代码片段 。
from collections import UserDictclass MyDict(UserDict):def __setitem__(self, key, value):super().__setitem__key, value * 5)d = MyDict({'one': 1, 'two': 2})print(d)#output: {'one': 5, 'two': 10}还可以随时覆盖其他函数,如__setitem__()、__getitem__()和__delitem__(),以进一步自定义字典的行为 。
四、总结在本文中,介绍了可以在不同情况下使用的不同类型的Python字典 。尽管很多Python开发者只使用常规字典,但也可以在项目中尝试使用其他类型的Python字典 。如果没有适合的字典,可以使用UserDict类来创建自己的类似字典的类 。




推荐阅读