设置为 dict Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18634650/
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-19 11:17:13  来源:igfitidea点击:

Set to dict Python

pythondictionaryset

提问by Sven Bamberger

is there any pythonic way to convert a set into a dict?

有没有任何pythonic方法可以将集合转换为字典?

I got the following set

我得到了以下套装

s = {1,2,4,5,6}

and want the following dict

并想要以下字典

c = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}

with a list you would do

有一个你会做的清单

a = [1,2,3,4,5,6]
b = []

while len(b) < len(a):
   b.append(0)

c = dict(itertools.izip(a,b))

采纳答案by Martijn Pieters

Use dict.fromkeys():

使用dict.fromkeys()

c = dict.fromkeys(s, 0)

Demo:

演示:

>>> s = {1,2,4,5,6}
>>> dict.fromkeys(s, 0)
{1: 0, 2: 0, 4: 0, 5: 0, 6: 0}

This works for lists as well; it is the most efficient method to create a dictionary from a sequence. Note all values are references to that one default you passed into dict.fromkeys(), so be careful when that default value is a mutable object.

这也适用于列表;这是从序列创建字典的最有效方法。请注意,所有值都是对您传入的默认值的引用dict.fromkeys(),因此当该默认值是可变对象时要小心。

回答by papirrin

Besides the method given by @Martijn Pieters, you can also use a dictionary comprehension like this:

除了@Martijn Pieters给出的方法,您还可以使用这样的字典理解:

s = {1,2,4,5,6}
d = {e:0 for e in s}

This method is slower than dict.fromkeys(), but it allows you to set the values in the dict to whatever you need, in case you don't always want it to be zero.

此方法比 dict.fromkeys() 慢,但它允许您将 dict 中的值设置为您需要的任何值,以防您不总是希望它为零。

You can also use it to create lists, lists comprehensions are faster and more pythonic that the loop that you have in your question. You can learn more about comprehensions here: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

您还可以使用它来创建列表,与您在问题中的循环相比,列表推导式更快、更具有 Python 风格。您可以在此处了解有关理解的更多信息:http: //docs.python.org/2/tutorial/datastructures.html#list-comprehensions

回答by asit_dhal

This is also another way to do

这也是另一种方式

s = {1,2,3,4,5}
dict([ (elem, 0) for elem in s ])