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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

{'Cyware': None, 'Paras': None, 'Jain': None}

 
Method #2 : Using dictionary comprehension



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

{'Paras': None, 'Jain': None, 'Cyware': None}

 
Method #3 : Using zip() function

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

{'Cyware': None, 'Paras': None, 'Jain': None}

 
Method #4 : Using fromkeys() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

{'Cyware': None, 'Jain': None, 'Paras': None}

 



My Personal Notes arrow_drop_up


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.