Home > Net >  Swap position of keys in a dictionary for same value
Swap position of keys in a dictionary for same value

Time:12-06

I have a dictionary

cost = {
        (0,1):70,
        (0,2):40,
        (1,2):65
        }

I would like a dictionary where the values for the opposite keys are also the same. To clarify,

(0,1):70 is also the same as (1,0):70

I tried to flip the values of the keys using this:

for i,j in cost.keys():
    cost [j,i]==cost[i,j]

This gives a key error of (1,0) but that is the key that I want the code to add.

I further tried cost1 = {tuple(y): x for x, y in cost.keys()} This resulted in a TypeError:'int' object not iterable

How can I then further append all the values to a dictionary? Thank you for your time and help.

CodePudding user response:

Try this code snippet, to see if that's what you want:

# make a new dict to reflect the swap keys:
cost1 = {}

for key, val in cost.items():
    x, y = key               # unpack the key
    cost1[(y, x)] = val      # swap x, y - tuple as the new key
    
print(cost1)
# {(1, 0): 70, (2, 0): 40, (2, 1): 65}
  • Related