50

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

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))
Sven Bamberger
  • 899
  • 2
  • 10
  • 21

3 Answers3

94

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
21

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

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.

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

Community
  • 1
  • 1
papirrin
  • 2,004
  • 22
  • 30
  • 2
    This is the method to use if the default value is mutable and you need a new object for each key. `dict.fromkeys()` is *far* faster otherwise. – Martijn Pieters Sep 05 '13 at 11:13
  • 2
    See [Most Pythonic Way to Build Dictionary From Single List](http://stackoverflow.com/q/14258984) for a comparison. – Martijn Pieters Sep 05 '13 at 11:16
  • True, comprehensions are slower. – papirrin Sep 05 '13 at 11:17
  • @MartijnPieters I just timed it and got a factor of 1.5x for `set(xrange(6))` and a factor of 3x for `set(xrange(10000))`. Definitely faster and there's no reason not to use `fromkeys`, but the difference isn't _that_ huge and this is pretty unlikely to be a bottleneck. – Danica Sep 16 '13 at 04:21
7

This is also another way to do

s = {1,2,3,4,5}
dict([ (elem, 0) for elem in s ])
asit_dhal
  • 1,239
  • 19
  • 35