Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simple way to convert list into dict with False values

What is a simple way to convert some list like l = ['a', 'b', 'c'] into some dict of following form d = {'a': False, 'b': False, 'c': False}?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As enke suggested you can use fromkeys method of dict class to convert the list or any other iterable into a dict by a fixed value for all keys.

In [1]: a = [1,2, "hello"]                                                                                                                                                      

In [2]: dict.fromkeys(a, False)                                                                                                                                                 
Out[2]: {1: False, 2: False, 'hello': False}

And also you can use dict comprehension as below:

In [1]: a = [1,2, "hello"]                                                                                                                                                      

In [2]: {key: False for key in a}                                                                                                                                               
Out[2]: {1: False, 2: False, 'hello': False}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading