This tutorial will discuss about a unique way to create a Dictionary with values in Python.
Suppose we have a list of values,
values = ['Ritika', 'Smriti', 'Mathew', 'Justin']
We want to create a dictionary from these values. But as a dictionary contains key-value pairs only, so what will be the key so in our case?
We want the keys to be incrementing integer values. Like,
- For the first value, the key should be 1.
- For the second value key should be 2.
- For the third value key should be 3.
- For the Nth value key should be N.
Using a Dictionary Comprehension, we will iterate from index zero till N. Where N is the number of values in the list. During iteration, for each index we will pick the ith value from the list and add a key-value pair in the dictionary using the Dictionary Comprehension.
Let’s see the complete example,
# Define a list of values values = ['Ritika', 'Smriti', 'Mathew', 'Justin'] # Create a dictionary with incrementing keys # and the values from the List dictObj = {i+1: values[i] for i in range(len(values))} # Print the dictionary print(dictObj)
Output
Frequently Asked:
- Python: Iterate over a dictionary sorted by value
- Create a Python Dictionary with values
- Python: Check if value exists in list of dictionaries
- Create CSV file from List of Dictionaries in Python
{1: 'Ritika', 2: 'Smriti', 3: 'Mathew', 4: 'Justin'}
Summary
We learned how to create a Dictionary with values in Python.