This tutorial will discuss about unique ways to create dictionary with predefined keys in Python.
Table Of Contents
Create Python Dictionary with Predefined Keys & a default value
Suppose we have a list of predefined keys,
keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']
We want to create a dictionary from these keys.
Dictionary should have all the keys specified in the list. But as a dictionary contains this key-value pairs, therefore value of each key will be a default value.
Frequently Asked:
For that we will use the fromkeys() method of the dictionary to create a dictionary. In this method, we will pass the list of keys as the first argument and the default value is the second argument. It will return as a dictionary initialised with key value pairs, where keys will be picked the given list, and each key will have the same specified default value.
Let’s see the complete example,
# A List of Keys keys = ['Ritika', 'Smriti', 'Mathew', 'Justin'] # Default value for each Key value = 10 # Create a Dictionary with the keys from list and a default value students = dict.fromkeys(keys, value) # Print the Dictionary print(students)
Output
{'Ritika': 10, 'Smriti': 10, 'Mathew': 10, 'Justin': 10}
Create Python Dictionary with Predefined Keys & auto incremental value
Suppose we have a list of predefined keys,
Latest Python - Video Tutorial
keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']
We want to create a dictionary from these keys, but the value of each key should be an integer value. Also the values should be the incrementing integer value in the dictionary. Like,
- For the first Key, the value should be 1.
- For the second Key, the value should be 2.
- For the third Key, the value should be 3.
- For the Nth Key, the value should be N.
Using a Dictionary Comprehension, we will iterate from index zero till N. Where N is the number of keys in the list. During iteration, for each index we will pick the ith Key from the list and add a key-value pair in the dictionary using the Dictionary Comprehension
Let’s see the complete example,
# A List of Keys keys = ['Ritika', 'Smriti', 'Mathew', 'Justin'] # Create a dictionary with incrementing # values for the keys from list students = {keys[i]: i+1 for i in range(len(keys))} # Print the Dictionary print(students)
Output
{'Ritika': 1, 'Smriti': 2, 'Mathew': 3, 'Justin': 4}
Summary
We learned how to create a Dictionary With Predefined Keys in Python.
Latest Video Tutorials