Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
zz9321 Avatar asked Sep 14 '26 15:09

zz9321


1 Answers

The power of python:

key1, key2 = random.sample(list(d), 2)
d[key1], d[key2] = d[key2], d[key1]
like image 145
simonzack Avatar answered Sep 17 '26 03:09

simonzack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!