python - 在Python中将列表转换为字典

标签 python list python-3.x dictionary

我问了很多问题,但找不到我要找的东西。 我有一个类似这样的列表: [2, 3, 5, 7, 11]
我想将它转换成以下格式的字典: 即列表的值应该是键,并且每个关联的值应该为零。 {2:0 , 3:0 , 5:0 , 7:0 , 11:0}

最佳答案

听写理解就可以了。

my_list = [2, 3, 5, 7, 11]
my_dict = {k: 0 for k in my_list}  # {2:0 , 3:0 , 5:0 , 7:0 , 11:0}

即使您根本不熟悉推导式,您仍然可以执行显式的 for 循环:

my_dict = {}
for k in my_list:
    my_dict[k] = 0

关于python - 在Python中将列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720875/

相关文章:

python - 如何在 python 关闭时调试异常

python - python3 : list vs List中的静态类型

Python,如何在列表末尾不需要额外的空间?

python-3.x - 在ubuntu上安装没有pip的python

Python Seg Fault 对我来说毫无意义

python - 如何使用 BeautifulSoup 从网页中获取整个正文文本?

python-3.x - 交叉验证时如何获取AUC-ROC而不是准确率?

python - Django user.save() 在列 'is_superuser' 上失败不能为空

python - Django/Python 使用 shell (os.system/Popen) 转换 PDF 在生产中不起作用

python - 鸭打字麻烦。 "i-am-like-a-list"的鸭子打字测试