Q:

Python program to swap the position of dictionary items

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now