使用 Python 在有序字典的開頭處插入
如果需要在有序字典的開頭處插入元素,可以使用“update”方法。
以下是其演示 −
示例
from collections import OrderedDict
my_ordered_dict = OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
print("The dictionary is :")
print(my_ordered_dict)
my_ordered_dict.update({'Mark':'7'})
my_ordered_dict.move_to_end('Mark', last = False)
print("The resultant dictionary is : ")
print(my_ordered_dict)輸出
The dictionary is :
OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
The resultant dictionary is :
OrderedDict([('Mark', '7'), ('Will', '1'), ('James', '2'), ('Rob', '4')])說明
匯入必需的包。
使用 OrderedDict’建立有序字典。
在控制檯上顯示它。
使用“update”方法指定鍵和值。
使用“move_to_end”方法將鍵值對移動到末尾。
在控制檯上顯示輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP