使用随机值构建字典的Python程序
给定 List,我们的任务是编写一个Python程序来构造字典,其中的值是从范围中随机选择的。
例子:
Input : test_list = ["Gfg", "is", "Best"], i, j = 2, 9
Output : {'Gfg': 3, 'is': 9, 'Best': 4}
Explanation : Random values assigned between 2 and 9.
Input : test_list = ["Gfg", "is", "Best"], i, j = 2, 10
Output : {'Gfg': 3, 'is': 9, 'Best': 10}
Explanation : Random values assigned between 2 and 10.
方法 #1:使用randint() +循环
在此,我们遍历列表中的每个元素并分配使用 randint() 选择的随机数来构造键值对字典。
Python3
# Python3 code to demonstrate working of
# Construct dictionary using random values
# Using randint() + loop
from random import randint
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 9
res = dict()
for ele in test_list:
# assigning random elements
res[ele] = randint(i, j)
# printing result
print("Random range initialized dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Construct dictionary using random values
# Using randint() + loop
from random import randint
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 9
# assigning random elements
# dictionary comprehension used as shorthand
res = {ele : randint(i, j) for ele in test_list}
# printing result
print("Random range initialized dictionary : " + str(res))
输出:
The original list is : [‘Gfg’, ‘is’, ‘Best’]
Random range initialized dictionary : {‘Gfg’: 5, ‘is’: 7, ‘Best’: 8}
方法 #2:使用字典理解+ randint()
在这种情况下,我们以与上述方法类似的方式执行任务,唯一的区别是使用字典理解以速记方式分配字典。
蟒蛇3
# Python3 code to demonstrate working of
# Construct dictionary using random values
# Using randint() + loop
from random import randint
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 9
# assigning random elements
# dictionary comprehension used as shorthand
res = {ele : randint(i, j) for ele in test_list}
# printing result
print("Random range initialized dictionary : " + str(res))
输出:
The original list is : [‘Gfg’, ‘is’, ‘Best’]
Random range initialized dictionary : {‘Gfg’: 4, ‘is’: 2, ‘Best’: 6}