Python – Shuffle 字典值
给定一个字典,任务是编写一个Python程序来将其值打乱到不同的键。
例子:
Input: test_dict = {“gfg” : 1, “is” : 7, “best” : 8, “for” : 3, “geeks” : 9}
Output : {“gfg” : 9, “is” : 8, “best” : 7, “for” : 3, “geeks” : 1}
Explanation : Keys are at same position but values are shuffled.
Input : test_dict = {“gfg” : 7, “is” : 1, “best” : 8, “for” : 3, “geeks” : 9}
Output : {“gfg” : 9, “is” : 8, “best” : 7, “for” : 3, “geeks” : 1}
Explanation : Keys are at same position but values are shuffled.
方法 #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))
输出:
The original dictionary is : {‘gfg’: 1, ‘is’: 7, ‘best’: 8, ‘for’: 3, ‘geeks’: 9}
The shuffled dictionary : {‘gfg’: 1, ‘is’: 7, ‘best’: 3, ‘for’: 9, ‘geeks’: 8}
方法 #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))
输出:
The original dictionary is : {‘gfg’: 1, ‘is’: 7, ‘best’: 8, ‘for’: 3, ‘geeks’: 9}
The shuffled dictionary : {‘gfg’: 8, ‘is’: 9, ‘best’: 1, ‘for’: 3, ‘geeks’: 7}