bdhar
bdhar

Reputation: 22973

Dict construction with elements in a list

I have a list ['a','b','c','d']. I need to construct a dict out of this list with all the elements of the list as keys in the dict with some default value for all the elements such as None.

How to do that? Should I need to write a function for that or is there a constructor available?

Upvotes: 3

Views: 1273

Answers (4)

Alok Singhal
Alok Singhal

Reputation: 96131

You can try:

dict.fromkeys(data, default_value)

If you omit default_value, it defaults to None.

Upvotes: 2

m-sharp
m-sharp

Reputation: 17115

lst = ['a','b','c','d']

# using list comprehension
d = dict([(x, None) for x in lst])

# using fromkeys
d = dict.fromkeys(lst)

Upvotes: 1

Gabe
Gabe

Reputation: 86718

See dict.fromkeys().

dict.fromkeys(['a','b','c','d']) will return a dictionary with None for all of its values.

dict.fromkeys(['a','b','c','d'], foo) will return a dictionary with foo for all of its values.

Upvotes: 6

Sunjay Varma
Sunjay Varma

Reputation: 5115

You can use a generator to quickly convert it to a dictionary:

dict((x, None) for x in L)

(Where L is your list)

That results in:

{'a': None, 'c': None, 'b': None, 'd': None}

Upvotes: 2

Related Questions