Set to dict Python

前端 未结 3 865
轮回少年
轮回少年 2021-02-03 17:59

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

<         


        
3条回答
  •  名媛妹妹
    2021-02-03 18:52

    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

提交回复
热议问题