Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set to dict Python

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)) 
like image 841
Sven Bamberger Avatar asked Sep 05 '13 11:09

Sven Bamberger


People also ask

Can set be dict keys Python?

Yes. According to the docs, Frozenset is hashable because it's immutable. This would imply that it can be used as the key to a dict, because the prerequisite for a key is that it is hashable.

Can you convert a set to a dictionary in Python?

To convert Python Set to Dictionary, use the fromkeys() method. The fromkeys() is an inbuilt function that creates a new dictionary from the given items with a value provided by the user. Dictionary has a key-value data structure. So if we pass the keys as Set values, then we need to pass values on our own.

Is dict () and {} the same?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


2 Answers

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.

like image 169
Martijn Pieters Avatar answered Sep 18 '22 04:09

Martijn Pieters


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

like image 21
papirrin Avatar answered Sep 19 '22 04:09

papirrin