欢迎访问宙启技术站
智能推送

Python编写的生成随机字典的技巧

发布时间:2023-12-11 06:07:23

生成随机字典是在Python编程中非常常见的需求之一。为了满足这个需求,可以使用Python的random库来生成随机数,然后根据需要构建字典。

下面是一些生成随机字典的技巧,以及带有使用例子的代码。

1. 生成随机字符串作为字典的键:

可以使用random库的choice方法从一个字符串中随机选择一个字符,然后将这个字符添加到一个空字符串中,重复这个过程指定次数,从而生成一个随机字符串。将生成的随机字符串作为键,可以创建一个包含随机键的字典。

import random

def generate_random_string(length):
    letters = "abcdefghijklmnopqrstuvwxyz"
    result = ""
    for _ in range(length):
        result += random.choice(letters)
    return result

random_dict = {}
for _ in range(10):
    key = generate_random_string(5)
    value = random.randint(1, 100)
    random_dict[key] = value

print(random_dict)

输出结果为:

{'xwdvn': 33, 'knorl': 53, 'qbidj': 59, 'kvusq': 14, 'mjgqg': 94, 'sgdpv': 68, 'unxlw': 15, 'jnxby': 49, 'eflge': 11, 'ikudy': 80}

2. 生成随机整数作为字典的值:

可以使用random库的randint方法生成指定范围内的随机整数,然后将生成的随机整数作为字典的值。

import random

random_dict = {}
for key in range(10):
    value = random.randint(1, 100)
    random_dict[key] = value

print(random_dict)

输出结果为:

{0: 30, 1: 90, 2: 39, 3: 17, 4: 64, 5: 49, 6: 55, 7: 75, 8: 88, 9: 60}

3. 生成随机列表作为字典的值:

可以使用random库的sample方法从指定列表中随机选择指定个数的元素,然后将生成的随机列表作为字典的值。

import random

random_dict = {}
for key in range(10):
    value = random.sample(range(1, 100), 5)
    random_dict[key] = value

print(random_dict)

输出结果为:

{0: [79, 95, 69, 8, 56], 1: [41, 52, 47, 36, 13], 2: [59, 20, 86, 83, 75], 3: [54, 80, 20, 74, 44], 4: [64, 66, 87, 89, 95], 5: [36, 59, 77, 84, 61], 6: [80, 38, 79, 89, 17], 7: [72, 45, 91, 43, 7], 8: [30, 31, 88, 79, 44], 9: [54, 20, 45, 55, 43]}

4. 生成随机字典中指定键值对数量的技巧:

可以使用random库的randrange方法来生成一个指定范围内的随机数,然后根据这个随机数循环添加键值对到字典中。

import random

random_dict = {}
num_entries = random.randrange(5, 15)  # 生成5到15之间的随机数

for _ in range(num_entries):
    key = generate_random_string(5)
    value = random.randint(1, 100)
    random_dict[key] = value

print(random_dict)

输出结果为:

{'iofha': 45, 'bmrcf': 19, 'twpzs': 85, 'evrxg': 72, 'owhxp': 91, 'pqryo': 27, 'dshzj': 83, 'qrqob': 67, 'mlxyv': 72, 'tlpti': 63, 'zzdyg': 75}

以上就是一些生成随机字典的技巧和使用例子,希望对你有所帮助!