python - 通过枚举函数创建python字典

标签 python

我正在寻找一种更简单的方法来创建这个 Python 字典。我可以知道枚举函数是否有帮助吗?

a_dict = {'a':0, 'b':1, 'c':2, ....}

最佳答案

使用 enumerate 你可以使用 generator expressionstring.ascii_lowercasewithindict 中:

>>> import string
>>> dict((j,i) for i,j in enumerate(string.ascii_lowercase))
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25}

由于 enumerate 返回格式为 (index,element) 的元组,您可以遍历它,只需用元素更改索引,然后将其转换为字典。

关于python - 通过枚举函数创建python字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30683950/

相关文章:

python - 使用 Django 和 PostgreSQL 查询二进制数据

python - 有没有关于基于 XML 的 API、REST、SOAP with Python 的好书和/或教程?

python - 如何创建不针对本地时间进行调整的 unix 时间戳?

python - Celery未注册任务KeyError

Python type() 函数返回一个可调用对象

python - 如何将两个相似的 View 组合成一个响应?

python - Qt Designer和PyQt程序中verticalLayout的大小不同

Python 类型检查协议(protocol)和描述符

python - PyPI 贝塞尔曲线 0.8.0 : Minimum number of points needed to plot a smooth bezier curve?

python - 用装饰器包装的函数的关键字参数不起作用