Python program to swap the position of dictionary items

Here, we are going to learn how to swap the position of dictionary items of the given index value in Python?
Submitted by Shivang Yadav, on March 25, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

Here, we have a dictionary and two values whose position is to be swapped.

For this, we will convert the list into a list of tuples using items() method. Then, we will swap the values in this list using the swapping method. Then, we will convert the list back to a dictionary and print it.

Program to swap the position of dictionary items

# Python program to swap the position 
# of dictionary items

# Initialising dictionary and swapping positions 
myDict = {'Scala': 2, 'Javascript': 5, 'Python': 8, 'C++': 1, 'Java': 4}
i, j = 2, 4

# Swapping Values for the given positions... 
tupList = list(myDict.items())
tupList[i], tupList[j] = tupList[j], tupList[i]
swappedDist = dict(tupList)

# Printing the dictionaries...
print("Initial dictionary = ", end = " ")
print(myDict)
print("Dictionary after swapping = ", end = " ")
print(swappedDist)

Output:

Initial dictionary =  {'Scala': 2, 'C++': 1, 'Python': 8, 'Java': 4, 'Javascript': 5}
Dictionary after swapping =  {'Scala': 2, 'C++': 1, 'Python': 8, 'Java': 4, 'Javascript': 5}

Explanation:

In the above code, we have a dictionary myDict, and i & j (the positions for swapping). For swapping we have converted the dictionary to a list of tuples tupList using list() method for each key-value pair of the dictionary using items() function.

Then we have swapped the values and converted the list back to a dictionary using dict() method.

Python Dictionary Programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.