Python – 在 OrderedDict 的开头插入
给定一个有序字典,编写一个程序在有序字典的开头插入项目。
例子 -
Input:
original_dict = {'a':1, 'b':2}
item to be inserted ('c', 3)
Output: {'c':3, 'a':1, 'b':2}
Input:
original_dict = {'akshat':1, 'manjeet':2}
item to be inserted ('nikhil', 3)
Output: {'nikhil':3, 'akshat':1, 'manjeet':2}
以下是在有序字典的开头插入项目的各种方法。
方法 #1:使用 OrderedDict.move_to_end()
Python3
# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# initialising ordered_dict
iniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
# inserting items in starting of dict
iniordered_dict.update({'manjeet':'3'})
iniordered_dict.move_to_end('manjeet', last = False)
# print result
print ("Resultant Dictionary : "+str(iniordered_dict))
Python3
# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# initialising ordered_dict
ini_dict1 = OrderedDict([('akshat', '1'), ('nikhil', '2')])
ini_dict2 = OrderedDict([("manjeet", '4'), ("akash", '4')])
# adding in beginning of dict
both = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items()))
# print result
print ("Resultant Dictionary :"+str(both))
输出:
Resultant Dictionary : OrderedDict([(‘manjeet’, ‘3’), (‘akshat’, ‘1’), (‘nikhil’, ‘2’)])
方法#2:使用朴素的方法
此方法仅适用于唯一键的情况
Python3
# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# initialising ordered_dict
ini_dict1 = OrderedDict([('akshat', '1'), ('nikhil', '2')])
ini_dict2 = OrderedDict([("manjeet", '4'), ("akash", '4')])
# adding in beginning of dict
both = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items()))
# print result
print ("Resultant Dictionary :"+str(both))
输出:
Resultant Dictionary :OrderedDict([(‘manjeet’, ‘4’), (‘akash’, ‘4’), (‘akshat’, ‘1’), (‘nikhil’, ‘2’)])