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
Python3
# 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) |
{'Cyware': None, 'Paras': None, 'Jain': None}
Method #2 : Using dictionary comprehension
Python3
# 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) |
{'Paras': None, 'Jain': None, 'Cyware': None}
Method #3 : Using zip() function
Python3
# 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) |
{'Cyware': None, 'Paras': None, 'Jain': None}
Method #4 : Using fromkeys() method
Python3
# 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) |
{'Cyware': None, 'Jain': None, 'Paras': None}
Method #5 : Using the dict.__init__ method:
Here is another approach to creating a dictionary with only keys from a list, using the dict.__init__ method:
Python3
def create_dict(key_list): # Initialize an empty dictionary d = {} # Use the dict.__init__ method to add the keys from the input list to the dictionary d.__init__( zip (key_list, [ None ] * len (key_list))) return d key_list = [ "Paras" , "Jain" , "Cyware" ] print (create_dict(key_list)) # {'Paras': None, 'Jain': None, 'Cyware': None} #This code is contributed by Edula Vinay Kumar Reddy |
{'Paras': None, 'Jain': None, 'Cyware': None}
This approach uses the dict.__init__ method to initialize the dictionary with the keys from the input list and None as the values.
The time complexity of the create_dict function is O(n), where n is the number of keys in the input list. This is because the function iterates through the input list once, and performs a constant number of operations on each iteration.
The space complexity of the create_dict function is also O(n), because the function creates a new dictionary with n keys. Additionally, the function creates a list of n None values to pass as the values for the keys in the dictionary.
Please Login to comment...