📜  Python|获取随机字典对

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

Python|获取随机字典对

有时,在使用字典时,我们可能会遇到需要从字典中随机查找一对的情况。这种类型的问题可能出现在诸如彩票等游戏中。让我们讨论一下可以执行此任务的某些方法。

方法 #1:使用 random.choice() + list() + items()
上述方法的组合可用于执行此任务。选择函数执行随机值选择的任务,列表方法用于将使用 items() 访问的对转换为选择函数可以工作的列表。警告,如果字典包含许多值,重复将其转换为列表可能会导致性能问题。

Python3
# Python3 code to demonstrate working of
# Get random dictionary pair in dictionary
# Using random.choice() + list() + items()
import random
 
# Initialize dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Get random dictionary pair in dictionary
# Using random.choice() + list() + items()
res = key, val = random.choice(list(test_dict.items()))
 
# printing result
print("The random pair is : " + str(res))


Python3
# Python3 code to demonstrate working of
# Get random dictionary pair in dictionary
# Using popitem()
 
# Initialize dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Get random dictionary pair in dictionary
# Using popitem()
res = test_dict.popitem()
 
# printing result
print("The random pair is : " + str(res))


输出 :
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)


方法 #2:使用 popitem()
此函数通常用于从字典中删除项目并将其删除。这个函数可以用来执行这个任务的逻辑是字典中的排序不依赖于插入项目的顺序。但是,重要的是要注意,在较新版本的Python中,同一组项目的顺序总是相同的。

Python3

# Python3 code to demonstrate working of
# Get random dictionary pair in dictionary
# Using popitem()
 
# Initialize dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Get random dictionary pair in dictionary
# Using popitem()
res = test_dict.popitem()
 
# printing result
print("The random pair is : " + str(res))
输出 :
The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}
The random pair is : ('is', 2)