Search code examples
pythondictionarykey-value-store

Swap two random values in dictionary


I have a dictionary that looks like this:

{'new': 'old', 'bright': 'dark', 'on': 'off'...}

How can I 'swap' two of the values at random? So for example, it might look like this afterwards:

{'new': 'dark', 'bright': 'old', 'on': 'off'...}

The order of the items is not important.

Edit:

This is what I had tried before asking:

keys = ['new', 'bright', 'on'...]
values = ['old', 'dark', 'off'...]
d = dict(zip(keys,values))
random.shuffle(values)
d = dict(zip(keys,values))

So, I suppose in essence, the problem was that I was able to shuffle all values, but not to swap just two of them at random.

Perhaps there was no need to mention that order is not important. When I was looking at similar questions, the authors seemed to want to locate and swap specific values of specific keys. That was not the case here, so really I was just referencing the fact that I had considered the 'orderlessness' of dictionaries.

Thank you for your comments, and for the solution.


Solution

  • The power of python:

    key1, key2 = random.sample(list(d), 2)
    d[key1], d[key2] = d[key2], d[key1]