python - 从变量名或字符串创建列表或字典

标签 python python-3.x dictionary

我正在尝试用 python 创建字典或列表。 创建字典的正常方法是 test = {} 但我不想将字典命名为 test 。 例如,我想将字典命名为我生成的随机哈希。

bagel = "bagels" 
h = hashlib.md5()
h.update(bagel.encode('utf-8'))
print(h.hexdigest())

然后我想从 h.hexdigest 创建字典变量。

h.hexdigest() = {}

但这不会使用我刚刚生成的哈希创建字典。

有人知道我该怎么做吗?

最佳答案

如果您可以生成不以数字开头的随机哈希,那么您所要求的可能是可能的。 因此,仅当生成的十六进制数字不以数字开头时,以下代码才有效

bagel = "bagels" 
h = hashlib.md5()
h.update(bagel.encode('utf-8'))
temp = h.hexdigest()
exec("{0} = dict()".format(temp))

因此,为了使其适用于任何情况,我建议您添加一个常量字符串,如下所示

bagel = "bagels" 
h = hashlib.md5()
h.update(bagel.encode('utf-8'))
temp = h.hexdigest()
exec("const_{0} = dict()".format(temp))

关于python - 从变量名或字符串创建列表或字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417265/

相关文章:

python - 使用Scrapy获取整个网站的所有URL

python - 正则表达式解析二进制文件?

Python 安装位置 (Windows)

python - 将列表的第一个元素除以第二个元素,第三个元素除以第四个元素,依此类推

python - 如何使用列表来避免一遍又一遍地重复 'and/or' 运算符?

python - 如何将字符串的元素放入具有特定行为的列表中

python - 迭代字典列表

python - 如何在vispy中选择距离点击点最近的标记?

python - 使用其他列的索引值在 pandas 数据框中的一列中进行字符串索引

ios - NSMutableArray 为图像创建问题