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 keyskeyList = ["Paras", "Jain", "Cyware"] # initialize dictionaryd = {} # iterating through the elements of listfor i in keyList: d[i] = None print(d) |
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 KeyskeyList = ["Paras", "Jain", "Cyware"] # Using Dictionary comprehensionmyDict = {key: None for key in keyList}print(myDict) |
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 keyslistKeys = ["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 dictprint(dct) |
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 keysStudent = ["Paras", "Jain", "Cyware"] # using fromkeys() methodStudentDict = dict.fromkeys(Student, None) # printing dictionaryprint(StudentDict) |
Output:
{'Cyware': None, 'Jain': None, 'Paras': None}


