从可迭代创建字典

use*_*312 11 python dictionary

从iterable创建字典并为其分配一些默认值的最简单方法是什么?我试过了:

>>> x = dict(zip(range(0, 10), range(0)))
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为范围(0)不是可迭代的,因为我认为它不会(但我还是试过了!)

那我该怎么办呢?如果我做:

>>> x = dict(zip(range(0, 10), 0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: zip argument #2 must support iteration
Run Code Online (Sandbox Code Playgroud)

这也不起作用.有什么建议?

Jef*_*ado 18

在python 3中,您可以使用dict理解.

>>> {i:0 for i in range(0,10)}
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
Run Code Online (Sandbox Code Playgroud)

幸运的是,这已经在python 2.7中向后移植,因此也可以在那里使用.


use*_*312 16

你需要的dict.fromkeys方法,它完全符合你的要求.

来自文档:

fromkeys(...)
    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
    v defaults to None.
Run Code Online (Sandbox Code Playgroud)

所以你需要的是:

>>> x = dict.fromkeys(range(0, 10), 0)
>>> x
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
Run Code Online (Sandbox Code Playgroud)

  • 假设我想要等于某个列表中的条目的值,而不是常量值。怎么做?像这样:“{0: y[0], 1: y[1], ... }”,其中“y”是一个列表。 (3认同)