📜  Python – Shuffle 字典值

📅  最后修改于: 2022-05-13 01:55:15.618000             🧑  作者: Mango

Python – Shuffle 字典值

给定一个字典,任务是编写一个Python程序来将其值打乱到不同的键。

例子:

方法 #1:使用shuffle() + zip() + dict()

在这里,我们使用shuffle()执行混洗元素的任务,而zip()用于将混洗后的值映射到键。最后使用dict()将结果转换为字典。

Python3
# Python3 code to demonstrate working of
# Shuffle dictionary Values
# Using shuffle() + zip() + dict()
import random
  
# initializing dictionary
test_dict = {"gfg": 1, "is": 7, "best": 8, 
             "for": 3, "geeks": 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# shuffling values
temp = list(test_dict.values())
random.shuffle(temp)
  
# reassigning to keys
res = dict(zip(test_dict, temp))
  
# printing result
print("The shuffled dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# Shuffle dictionary Values
# Using sample() + zip()
from random import sample
  
# initializing dictionary
test_dict = {"gfg": 1, "is": 7, "best": 8, 
             "for": 3, "geeks": 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# reassigning to keys
res = dict(zip(test_dict, sample(list(test_dict.values()), 
                                 len(test_dict))))
  
# printing result
print("The shuffled dictionary : " + str(res))


输出:

方法 #2:使用sample() + zip()

在这里,混洗值的任务是使用随机库的sample()完成的。

蟒蛇3

# Python3 code to demonstrate working of
# Shuffle dictionary Values
# Using sample() + zip()
from random import sample
  
# initializing dictionary
test_dict = {"gfg": 1, "is": 7, "best": 8, 
             "for": 3, "geeks": 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# reassigning to keys
res = dict(zip(test_dict, sample(list(test_dict.values()), 
                                 len(test_dict))))
  
# printing result
print("The shuffled dictionary : " + str(res))

输出: