Skip to content
Related Articles

Related Articles

Python | Initialize a dictionary with only keys from a list

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 15 Feb, 2019
View Discussion
Improve Article
Save Article

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)

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)

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)

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)

Output:

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

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!