You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于密码生成可复现的Python编码字典

问题:实现基于密码种子的无预定义编解码字典编码器

需求说明

  • 无需预定义编解码字典,借助string库获取字符集
  • 以密码为随机种子,通过random库打乱生成编解码字典
  • 同一密码必须生成完全一致的字典

现有代码(仅支持打乱预定义字典)

import random

def shuffle_dict(password):
    # Create a dictionary with keys and values
    my_dict = {"a": "1", "b": "2", "c": "3", "d": "4"}

    # Convert the password string to a list of characters
    password_list = list(password)

    # Shuffle the list of characters using the password as a seed
    random.seed(password)
    random.shuffle(password_list)

    # Create a new dictionary with shuffled values
    shuffled_dict = {}
    for i, key in enumerate(my_dict.keys()):
        shuffled_dict[key] = password_list[i]

    return shuffled_dict

# Example usage
password = "HEFNJGBADI"
shuffled_dict = shuffle_dict(password)
print(shuffled_dict)

解决方案

以下是满足需求的完整实现,核心思路是基于string库构建字符集,通过密码种子打乱值集合来生成映射字典:

import random
import string

def generate_cipher_dict(password, charset=None):
    # 自定义字符集,默认包含小写字母、数字和常用标点符号
    if charset is None:
        charset = string.ascii_lowercase + string.digits + string.punctuation
    
    # 去重并排序,确保不同环境下初始字符顺序一致
    charset = sorted(list(set(charset)))
    
    # 复制字符集分别作为键和值的来源
    keys = charset.copy()
    values = charset.copy()
    
    # 以密码为种子初始化随机数生成器,保证相同密码输出相同字典
    random.seed(password)
    # 打乱值列表
    random.shuffle(values)
    
    # 配对键与打乱后的值,生成编解码字典
    cipher_dict = dict(zip(keys, values))
    return cipher_dict

# 示例使用
if __name__ == "__main__":
    password = "ABC"
    cipher = generate_cipher_dict(password)
    # 打印前10组映射示例
    print("{")
    for idx, (key, val) in enumerate(list(cipher.items())[:10]):
        comma = "," if idx < 9 else ""
        print(f'  "{key}": "{val}"{comma}')
    print("  ...")
    print("}")

代码说明

  1. 字符集自定义:默认使用string库提供的小写字母、数字和标点,也可通过charset参数传入自定义字符集合
  2. 稳定性保障:对字符集排序后再处理,避免因set无序特性导致不同环境下初始键顺序不一致
  3. 可复现性:通过random.seed(password)绑定密码与随机序列,同一密码每次调用都会生成完全相同的字典
  4. 高效映射:用zip函数快速将键列表与打乱后的值列表配对生成字典,简洁高效

内容的提问来源于stack exchange,提问作者Siddharth Dhir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 09:38:13