Python - 在字典开头附加项目
给定一个字典,在它的开头附加另一个字典。
Input : test_dict = {“Gfg” : 5, “is” : 3, “best” : 10}, updict = {“pre1” : 4}
Output : {‘pre1’: 4, ‘Gfg’: 5, ‘is’: 3, ‘best’: 10}
Explanation : New dictionary updated at front of dictionary.
Input : test_dict = {“Gfg” : 5}, updict = {“pre1” : 4}
Output : {‘pre1’: 4, ‘Gfg’: 5}
Explanation : New dictionary updated at front of dictionary, “pre1” : 4.
方法 #1:使用 update()
这是可以执行此任务的方式之一。在此,我们使用更新函数在新字典之后更新旧字典,以便在开头附加新字典。
Python3
# Python3 code to demonstrate working of
# Append items at beginning of dictionary
# Using update()
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 3, "best" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing update dictionary
updict = {"pre1" : 4, "pre2" : 8}
# update() on new dictionary to get desired order
updict.update(test_dict)
# printing result
print("The required dictionary : " + str(updict))
Python3
# Python3 code to demonstrate working of
# Append items at beginning of dictionary
# Using ** operator
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 3, "best" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing update dictionary
updict = {"pre1" : 4, "pre2" : 8}
# ** operator for packing and unpacking items in order
res = {**updict, **test_dict}
# printing result
print("The required dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}
方法 #2:使用 **运算符
这是可以执行此任务的另一种方式。在此,我们使用 **运算符将项目打包和解包到定制字典中。
Python3
# Python3 code to demonstrate working of
# Append items at beginning of dictionary
# Using ** operator
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 3, "best" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing update dictionary
updict = {"pre1" : 4, "pre2" : 8}
# ** operator for packing and unpacking items in order
res = {**updict, **test_dict}
# printing result
print("The required dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}