随机随机播放Python DIctionary中的键和值

bre*_*ebs 1 python random dictionary shuffle

有没有办法随机洗牌哪些键对应什么值?我找到了random.sample,但我想知道是否有更多的pythonic /更快的方法.

例: a = {"one":1,"two":2,"three":3}

洗牌: a_shuffled = {"one":2,"two":3,"three":1}

unu*_*tbu 6

In [47]: import random

In [48]: keys = a.keys()

In [49]: values = a.values()

In [50]: random.shuffle(values)

In [51]: a_shuffled = dict(zip(keys, values))

In [52]: a_shuffled
Out[52]: {'one': 2, 'three': 1, 'two': 3}
Run Code Online (Sandbox Code Playgroud)

或者,更精辟的是:

In [56]: dict(zip(a.keys(), random.sample(a.values(), len(a))))
Out[56]: {'one': 3, 'three': 2, 'two': 1}
Run Code Online (Sandbox Code Playgroud)

(但我想这是你已经提出的解决方案.)


请注意,虽然使用random.sample更简单,但使用random.shuffle速度要快一些:

import random
import string
def using_shuffle(a):
    keys = a.keys()
    values = a.values()
    random.shuffle(values)
    return dict(zip(keys, values))

def using_sample(a):
    return dict(zip(a.keys(), random.sample(a.values(), len(a))))

N = 10000
keys = [''.join(random.choice(string.letters) for j in range(4)) for i in xrange(N)]
a = dict(zip(keys, range(N)))

In [71]: %timeit using_shuffle(a)
100 loops, best of 3: 5.14 ms per loop

In [72]: %timeit using_sample(a)
100 loops, best of 3: 5.78 ms per loop
Run Code Online (Sandbox Code Playgroud)