Python | Initialize a dictionary with only keys from a list
Given a List, the task is to create a dictionary with only keys by using given list as keys.
Let’s see the different methods we can do this task.
Method #1 : By iterating through list
# Python code to initialize a dictionary # with only keys from a list # List of keys keyList = ["Paras", "Jain", "Cyware"] # initialize dictionary d = {} # iterating through the elements of list for i in keyList: d[i] = None print(d) |
chevron_right
filter_none
Output:
{'Cyware': None, 'Paras': None, 'Jain': None}
Method #2 : Using dictionary comprehension
# Python code to initialize a dictionary # with only keys from a list # List of Keys keyList = ["Paras", "Jain", "Cyware"] # Using Dictionary comprehension myDict = {key: None for key in keyList} print(myDict) |
chevron_right
filter_none
Output:
{'Paras': None, 'Jain': None, 'Cyware': None}
Method #3 : Using zip() function
# Python code to initialize a dictionary # with only keys from a list # List of keys listKeys = ["Paras", "Jain", "Cyware"] # using zip() function to create a dictionary # with keys and same length None value dct = dict(zip(listKeys, [None]*len(listKeys))) # print dict print(dct) |
chevron_right
filter_none
Output:
{'Cyware': None, 'Paras': None, 'Jain': None}
Method #4 : Using fromkeys() method
# Python code to initialize a dictionary # with only keys from a list # List of keys Student = ["Paras", "Jain", "Cyware"] # using fromkeys() method StudentDict = dict.fromkeys(Student, None) # printing dictionary print(StudentDict) |
chevron_right
filter_none
Output:
{'Cyware': None, 'Jain': None, 'Paras': None}
Recommended Posts:
- Python | Initialize dictionary with multiple keys
- Python | Get dictionary keys as a list
- Python | Sort dictionary keys to list
- Python | Initialize common value to keys
- Python | Initialize dictionary with common value
- Python | Initialize dictionary with None values
- Python | Add new keys to a dictionary
- Python | Grouping dictionary keys by value
- Python | Count keys with particular value in dictionary
- Python Dictionary | keys() method
- Python | Minimum value keys in Dictionary
- Python | Get total keys in dictionary
- Python | Add keys to nested dictionary
- Python | Reversed Order keys in dictionary
- Python | Ways to change keys in dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



