Home > Back-end >  what is a python program to interchange first and last element of dictionary?
what is a python program to interchange first and last element of dictionary?

Time:12-08

how may we interchange the positions of first and last element in a dictionary. I tried to use the swap function which did'nt work quite well for me, what can i use to achieve my desired result, please answer.

CodePudding user response:

Here is one way of doing this, I'm sure there is an easier way but this method should work

# Example dictionary
test_dict = {'one': 1, 'two': 2, 'three': 3}

# initializing swap indices (-1 represents the last element)
i, j = 0, -1

# conversion to tuples
tups = list(test_dict.items())

# swapping by indices
tups[i], tups[j] = tups[j], tups[i]

# converting back
res = dict(tups)
print(res)

This returns...

{'three': 3, 'two': 2, 'one': 1}

CodePudding user response:

Another way is to use OrderedDict and its exclusive function move_to_end() which allows us to efficiently swap first and last elements of our dict:

from collections import OrderedDict

dct = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
odct = OrderedDict({'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5})
odct.move_to_end(list(dct.keys())[0])
odct.move_to_end(list(dct.keys())[-1], last=False)
print(dct)
print(dict(odct))

Output:

{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
{'five': 5, 'two': 2, 'three': 3, 'four': 4, 'one': 1}

CodePudding user response:

It is not clear if you meant to swap the sequence of the dictionary itself or just the values.

# dictionary value swap
test_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
test_dict['one'], test_dict['five']= test_dict['five'], test_dict['one']
print (test_dict)
Output:  {'one': 5, 'two': 2, 'three': 3, 'four': 4, 'five': 1}

You can also extract the first and last values (or any value) using keys.

test_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
mylist = list(test_dict.keys())
mylist[0],mylist[-1]=mylist[-1],mylist[0]
print (mylist)
Output:  ['five', 'two', 'three', 'four', 'one']

result_1, result_2 = test_dict[mylist[0]], test_dict[mylist[-1]] 
print (result_1, "Key in list swapped ", result_2)
Output:  5 Key in list swapped 1

print ("test_dict is unchange:", test_dict)
Output:  test_dict is unchange: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
  • Related