Open In App

Add Item after Given Key in Dictionary – Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of adding an item after a specific key in a Pythondictionary involves modifying the order of the dictionary’s key-value pairs. Since Python dictionaries maintain the insertion order, we can achieve this by carefully placing the new key-value pair after the target key. For example, consider a dictionary d = {‘a’: 1, ‘b’: 2, ‘c’: 3}. If the task is to add a new item ‘d’: 4 after the key ‘b’, the expected output will be {‘a’: 1, ‘b’: 2, ‘d’: 4, ‘c’: 3}.

Using dict.fromkeys()

This method is efficient because it avoids direct iteration over the dictionary. By using list slicing, we can split the dictionary into parts before and after the target key and then insert the new key-value pair at the correct location. The result is a new dictionary that preserves the insertion order.

Python
d = {'a': 1, 'b': 2, 'c': 3}
k, v = 'd', 4 # new key ('d') and value (4) 
tar = 'b' # target key

keys = list(d.keys())
values = list(d.values())
tar_idx = keys.index(tar) # index of the target key 'b'

a = keys[:tar_idx + 1] + [k] + keys[tar_idx + 1:]
b = values[:tar_idx + 1] + [v] + values[tar_idx + 1:]

res = dict(zip(a, b))
print(res)  

Output
{'a': 1, 'b': 2, 'd': 4, 'c': 3}

Explanation:

  • list(d.keys()) convert dictionary keys to a list [‘a’, ‘b’, ‘c’].
  • list(d.values()) convert dictionary values to a list [1, 2, 3].
  • keys[:tar_idx + 1] + [k] + keys[tar_idx + 1 inserts ‘d’ after ‘b’.
  • values[:tar_idx+1] + [v] + values[tar_idx+ 1:] inserts 4 after 2.
  • dict(zip(a, b)) combines the updated lists into a dictionaryres .

Using itertools.chain()

By splitting the dictionary into three parts, the items before the target key, the new key-value pair, and the items after the target key. We can merge them using itertools.chain(). This approach avoids manual iteration and provides an efficient solution for larger dictionaries.

Python
import itertools

d = {'a': 1, 'b': 2, 'c': 3}
k, v = 'd', 4  # new key ('d') and value (4) 
tar = 'b' # target key

li= list(d.items())
tar_idx = li.index((tar, d[tar])) # index of target key-value pair (tar, d[tar])

res = dict(itertools.chain(
    li[:tar_idx + 1],
    [(k, v)],
    li[tar_idx + 1:]
))

print(res)

Output
{'a': 1, 'b': 2, 'd': 4, 'c': 3}

Explanation:

  • list(d.items()) convert the dictionary d into a list of tuples.
  • li[:tar_idx + 1] gives [(‘a’, 1), (‘b’, 2)], items before‘b’.
  • [(k, v)] inserts the new item (‘d’, 4).
  • li[tar_idx + 1:] gives [(‘c’, 3)],items after ‘b‘.
  • Then result is combined into new dictionary res.

Using insert()

In this approach, we convert the dictionary to a list of tuples, find the index of the key after which we want to insert the new key-value pair, use insert() to add the new item and then convert the list back to a dictionary. This provides a simple yet effective way to insert the new item.

Python
d = {'a': 1, 'b': 2, 'c': 3}
k, v = 'd', 4   # new key ('d') and value (4)
tar = 'b'       # target key

items = list(d.items())

# index of the target key 'b'
tar_idx  = [i for i, (key, _) in enumerate(items) if key == tar][0]

items.insert(tar_idx + 1, (k, v))
res = dict(items)

print(res)

Output
{'a': 1, 'b': 2, 'd': 4, 'c': 3}

Explanation:

  • list(d.items()) convert the dictionary into a list of tuples.
  • items.insert(tar_idx + 1, (k, v)) insert the new item (‘d’, 4) after the target key ‘b‘.
  • dict(items) convert the updated list back into a dictionary res .

Using Loop

By iterating over the original dictionary, we can copy the existing items into a new dictionary. When the target key is found, we immediately insert the new key-value pair into the new dictionary. This approach provides flexibility and control but is less efficient than the other methods due to the explicit iteration over all items.

Python
d = {'a': 1, 'b': 2, 'c': 3}

k, v = 'd', 4  # new key ('d') and value (4) 
tar = 'b'  # target key

# initialize an empty dictionary
res = {}

for i, j in d.items():
  
    res[i] = j
    if i == tar:
        res[k] = v
        
print(res)

Output
{'a': 1, 'b': 2, 'd': 4, 'c': 3}

Explanation:

  • for i, j in d.items() loop through the dictionary d with each key-value pair (i, j).
  • res[i] = j add the current key-value pair to the new dictionary res .
  • if i == tar when the target key tar= ‘b’ is found, insert the new item ‘d’, 4 after it.
  • res[k] = v add the new key-value pair ‘d’, 4 to the dictionaryres .


Next Article
Practice Tags :

Similar Reads

  翻译: