简体   繁体   中英

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.

The power of python:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM