We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

How to Initialize a Dictionary with List in Python

This tutorial will discuss about a unique way to initialize a dictionary with list in Python.

Suppose you have a list of keys, and you want to initialize a dictionary with this List.

To initialise a dictionary with list of keys and a default value, we can use the fromkeys() method from the dictionary. We will pass the list of keys as first argument and the default value as the second argument in the fromkeys() method.

Advertisements

It will initialise, and return a dictionary object, where the items from the list listOfKeys will be the keys in the key-value pairs, and each key will have a default value, which we provided as second argument in the fromkeys() method.

In the belowe example, we will initialize a Dictionary with a list of strings, and a default value 11.

Let’s see the complete example,

listOfKeys = ['Sanjay', 'Aarav', 'Smriti', 'Mathew', 'John']

# Default Value
value = 11

# Create a Dictionary from List of keys
dictObj = dict.fromkeys(listOfKeys, value)

print(dictObj)

Output

{'Sanjay': 11, 'Aarav': 11, 'Smriti': 11, 'Mathew': 11, 'John': 11}

Summary

We learned how to Initialize a Dictionary with a List in Python.

Cart

Your Cart is Empty

Back To Shop