Python – Append items at beginning of dictionary
Last Updated :
05 May, 2023
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
test_dict = { "Gfg" : 5 , "is" : 3 , "best" : 10 }
print ( "The original dictionary is : " + str (test_dict))
updict = { "pre1" : 4 , "pre2" : 8 }
updict.update(test_dict)
print ( "The required dictionary : " + str (updict))
|
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
test_dict = { "Gfg" : 5 , "is" : 3 , "best" : 10 }
print ( "The original dictionary is : " + str (test_dict))
updict = { "pre1" : 4 , "pre2" : 8 }
res = { * * updict, * * test_dict}
print ( "The required dictionary : " + str (res))
|
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 #3 : Using for loop
Approach
- Initiate a for loop to traverse keys of test_dict
- Add keys and values of test_dict to updict using assignment operator =
- Display updict
Python3
test_dict = { "Gfg" : 5 , "is" : 3 , "best" : 10 }
print ( "The original dictionary is : " + str (test_dict))
updict = { "pre1" : 4 , "pre2" : 8 }
for i in list (test_dict.keys()):
updict[i] = test_dict[i]
print ( "The required dictionary : " + str (updict))
|
Output
The original dictionary is : {'Gfg': 5, 'is': 3, 'best': 10}
The required dictionary : {'pre1': 4, 'pre2': 8, 'Gfg': 5, 'is': 3, 'best': 10}
Time Complexity : O(N) N – length of test_dict
Auxiliary Space : O(N) N – length of updated dictionary up_dict
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...