Python – Append items at beginning of dictionary

Given a dictionary, append another dictionary at beginning of it.

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.

Method #1 : Using update()

This is one of the ways in which this task can be performed. In this, we use update function to update old dictionary after the new one so that new dictionary is appended at beginning.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}

Method #2 : Using ** operator

This is yet another way in which this task can be performed. In this, we perform packing and unpacking of items into custom made dictionary using ** operator.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.