Python 从可迭代对象创建字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4084749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:10:50  来源:igfitidea点击:

Creating a dictionary from an iterable

pythondictionary

提问by user225312

What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried:

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

>>> x = dict(zip(range(0, 10), range(0)))

But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)

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

So how do I go about it? If I do:

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

>>> 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

This doesn't work either. Any suggestions?

这也行不通。有什么建议?

采纳答案by user225312

You need the dict.fromkeysmethod, which does exactly what you want.

您需要该dict.fromkeys方法,它完全符合您的要求。

From the docs:

从文档:

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

So what you need is:

所以你需要的是:

>>> 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}

回答by Matthew Flaschen

PulpFiction gives the practical way to do it. But just for interest, you can make your solution work by using itertools.repeatfor a repeating 0.

PulpFiction 提供了实用的方法。但出于兴趣,您可以通过使用itertools.repeat重复的 0来使您的解决方案起作用。

x = dict(zip(range(0, 10), itertools.repeat(0)))

回答by Jeff Mercado

In python 3, You can use a dict comprehension.

在python 3中,您可以使用字典理解。

>>> {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}

Fortunately, this has been backported in python 2.7 so that's also available there.

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

回答by martineau

You may want to consider using the defaultdictsubclass from the standard library's collectionsmodule. By using it you may not even need to iterate though the iterable since keys associated with the specified default value will be created whenever you first access them.

您可能需要考虑使用defaultdict标准库collections模块中的子类。通过使用它,您甚至可能不需要遍历可迭代对象,因为与指定的默认值关联的键将在您第一次访问它们时创建。

In the sample code below I've inserted a gratuitous forloop to force a number of them to be created so the following print statement will have something to display.

在下面的示例代码中,我插入了一个无故for循环来强制创建其中的一些,这样下面的打印语句就会显示一些内容。

from  collections import defaultdict

dflt_dict = defaultdict(lambda:42)

# depending on what you're doing this might not be necessary...
for k in xrange(0,10):
    dflt_dict[k]  # accessing any key adds it with the specified default value

print dflt_dict.items()
# [(0, 42), (1, 42), (2, 42), (3, 42), ... (6, 42), (7, 42), (8, 42), (9, 42)]