Search code examples
pythondictionaryswap

How to swap key with other key in dictionary python (NOT with values)


I have a dictionary dct = {'one' : 1, 'two' : 2, 'three' : 3 } and would like to swap 'one' with 'two' like belows.

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

Is there any way to do this?


Solution

  • You can use python's typical multi-assignment swap pattern:

    dct["one"], dct["two"] = dct["two"], dct["one"]