Python - 在字典中给定键后添加项目
给定一个字典和一个键,在字典中的特定键之后添加新项目。
Input : test_dict = {“Gfg” : 3, “is” : 5, “for” : 8, “Geeks” : 10}, K = “is”, add_item = {“good” : 19}
Output : {‘Gfg’: 3, ‘is’: 5, ‘good’: 19, ‘for’: 8, ‘Geeks’: 10}
Explanation : Item added after desired key in dictionary.
Input : test_dict = {“Gfg” : 3, “is” : 5, “for” : 8, “Geeks” : 10}, K = “for”, add_item = {“good” : 19}
Output : {‘Gfg’: 3, ‘is’: 5, ‘for’: 8, ‘good’: 19, ‘Geeks’: 10}
Explanation : Item added after desired key in dictionary.
方法:使用循环+更新()
在这个我们迭代所有的键,当遇到目标键时,迭代被拖拽并且字典被更新为所需的键。然后继续迭代。
Python3
# Python3 code to demonstrate working of
# Dictionary Keys whose Values summation equals K
# Using loop + update()
# initializing dictionary
test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = "is"
# initializing dictionary to be added
add_item = {"best" : 19}
# using dictionary comprehension
res = dict()
for key in test_dict:
res[key] = test_dict[key]
# modify after adding K key
if key == K:
res.update(add_item)
# printing result
print("Modified dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': 3, 'is': 5, 'for': 8, 'Geeks': 10}
Modified dictionary : {'Gfg': 3, 'is': 5, 'best': 19, 'for': 8, 'Geeks': 10}