Open In App

Python – Add item after given Key in dictionary

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary and a Key, add new item after a particular key in dictionary.

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.

Method 1: Using loop + update()

In this we iterate for all the keys, and when target key is encountered, the iteration is halted and dictionary is updated with required key. Then iteration is resumed.

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))


Output

The original dictionary is : {'Gfg': 3, 'is': 5, 'for': 8, 'Geeks': 10}
Modified dictionary : {'Gfg': 3, 'is': 5, 'best': 19, 'for': 8, 'Geeks': 10}

Time Complexity: O(n), where n is the values in dictionary
Auxiliary Space: O(n), where n is the size of dictionary

Method 2: Using keys(),values(),items(),insert(),index() methods

Approach

  1. Access the keys and values of test_dict  using keys(),values()methods
  2. Insert the new key into keys list and value into values list after K using insert(),index() method
  3. Now create a new dictionary using keys list and values list by for loop
  4. Display the new dictionary

Python3




# Python3 code to demonstrate working of
# Dictionary Keys whose Values summation equals K
 
# 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}
res=dict()
a=list(add_item.items())
x=list(test_dict.keys())
y=list(test_dict.values())
x.insert(x.index(K)+1,a[0][0])
y.insert(x.index(K)+1,a[0][1])
for i in range(0,len(x)):
    res[x[i]]=y[i]
 
# printing result
print("Modified dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 3, 'is': 5, 'for': 8, 'Geeks': 10}
Modified dictionary : {'Gfg': 3, 'is': 5, 'best': 19, 'for': 8, 'Geeks': 10}

Time Complexity : O(N)
Auxiliary Space : O(N)

Method 3: Using dictionary comprehension and the get() method

  • Initialize the dictionary test_dict and the key K with their respective values.
  • Initialize the dictionary add_item with the key-value pair that needs to be added to the test_dict.
  • Calculate the sum of all values in the dictionary using the sum() method.
  • Check if the sum of all values is equal to K or not.
  • If the sum is equal to K, return the original dictionary as the result.
  • If the sum is not equal to K, add the new key-value pair to the dictionary and return the modified dictionary as the result.

Python3




# Python3 code to demonstrate working of
# Dictionary Keys whose Values summation equals K
# Using dictionary comprehension and get()
 
# 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 = 18
 
# initializing dictionary to be added
add_item = {"best" : 19}
 
# calculate the sum of all values in the dictionary
sum_values = sum(test_dict.values())
 
# check if the sum of all values is equal to K or not
if sum_values == K:
    res = test_dict
else:
    # add the new key-value pair to the dictionary
    test_dict.update(add_item)
 
    # return the modified dictionary
    res = test_dict
 
# printing result
print("Modified dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 3, 'is': 5, 'for': 8, 'Geeks': 10}
Modified dictionary : {'Gfg': 3, 'is': 5, 'for': 8, 'Geeks': 10, 'best': 19}

Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(1), as we are not using any extra space for computation.



Previous Article
Next Article

Similar Reads

Python | Remove item from dictionary when key is unknown
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss the various ways to remove items from the dictionary when key is unknown. Method #1 : Using n
6 min read
Python Remove Item from Dictionary by Key
A dictionary in Python is a mutable and dynamic data type that provides a flexible way to access and manipulate data. As distinct from a list or a tuple, where elements are accessed via indices, a dictionary leverages a unique key representing each item. In this article, we will see how to remove items from the dictionary by key in Python. Remove I
3 min read
Delete a Python Dictionary Item If the Key Exists
In Python, dictionaries are like containers that help us keep and find information easily. They use key-value pairs to organize data, making them super helpful. But sometimes, we need to get rid of something specific from the dictionary, like when we know the key. This article explores some simple ways to do that efficiently How To Delete A Diction
3 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Add a key:value pair to dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. While using Dictionary, sometimes, we need to add or modify the key/value inside the dictionary. Let's see how to add a key:value pair to dict
2 min read
Python - Add prefix to each key name in dictionary
Given a dictionary, update its every key by adding a prefix to each key. Input : test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9}, temp = "Pro" Output : {'ProGfg' : 6, 'Prois' : 7, 'Probest' : 9} Explanation : "Pro" prefix added to each key. Input : test_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9}, temp = "a" Output : {'aGfg' : 6, 'ais' : 7, 'abest' : 9}
4 min read
Add Key to Dictionary Python Without Value
In Python, dictionaries are a versatile and widely used data structure that allows you to store and organize data in key-value pairs. While adding a key to a dictionary is straightforward when assigning a value, there are times when you may want to add a key without specifying a value initially. In this article, we'll explore some simple methods to
3 min read
Add a Key-Value Pair to a Nested Dictionary in Python
Dictionaries in Python are versatile data structures that allow you to store and manipulate key-value pairs. When dealing with nested dictionaries, adding a key-value pair becomes a bit more intricate. In this article, we will explore four simple methods to add a key-value pair to a nested dictionary in Python. To illustrate these methods, we will
3 min read
Add Same Key in Python Dictionary
In Python, dictionaries are a versatile data structure that allows you to store key-value pairs. If we want to add the same key with a new value to a dictionary, there are multiple methods to achieve this. In this discussion, we will explore different methods for adding the same key with a new value to a dictionary. Add Same Key in the Dictionary i
3 min read
Practice Tags :