Set to dict Python

前端 未结 3 859
轮回少年
轮回少年 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:37

    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.

提交回复
热议问题