Python - Incremental value initialization in Dictionary
Last Updated :
09 Apr, 2023
The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index incremental with K difference. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using dictionary comprehension + enumerate() This problem can be solved easily using the combination of above functions, dictionary comprehension can perform the task of constructing the dictionary and enumerate function can be used to access the index value along with the element.
Python3
# Python3 code to demonstrate
# Incremental value initialization in Dictionary
# using Dictionary comprehension + enumerate()
# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
# printing original list
print("The original list : " + str(test_list))
# initialization K
K = 4
# using Dictionary comprehension + enumerate()
# Incremental value initialization in Dictionary
res = {val : (K * (idx + 1)) for idx, val in enumerate(test_list)}
# print result
print("The Dictionary after index keys : " + str(res))
Output : The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Akash': 12, 'Nikhil': 4, 'Manjeet': 16, 'Akshat': 8}
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the dictionary comprehension + enumerate which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using dict() + zip() This problem can also be solved using the combination of above 2 functions, the dict method can be used to convert to dictionary and zip function can be used to map the indices with the keys.
Python3
# Python3 code to demonstrate
# Incremental value initialization in Dictionary
# using dict() + zip()
# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
# printing original list
print("The original list : " + str(test_list))
# initialization K
K = 4
# using dict() + zip()
# Incremental value initialization in Dictionary
res = dict(zip(test_list, range(K, len(test_list) * (K + 1), K)))
# print result
print("The Dictionary after index keys : " + str(res))
Output : The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Akash': 12, 'Nikhil': 4, 'Manjeet': 16, 'Akshat': 8}
Time Complexity: O(n), where n is the values in dictionary
Auxiliary Space: O(n), where n is the size of dictionary
Method #3 : Using for loop
This method uses a for loop to iterate through the list and add key-value pairs to the dictionary.
Python3
# Python3 code to demonstrate
# Incremental value initialization in Dictionary
# using for loop
# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
# printing original list
print("The original list : " + str(test_list))
# initialization K
K = 4
# using for loop
# Incremental value initialization in Dictionary
res = {}
for i, val in enumerate(test_list):
res[val] = K * (i + 1)
# print result
print("The Dictionary after index keys : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 4, 'Akshat': 8, 'Akash': 12, 'Manjeet': 16}
Time complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), to store the dictionary of n key-value pairs
Method #4 : Using for loop + dict()
Python3
# Python3 code to demonstrate
# Incremental value initialization in Dictionary
# using for loop
# initializing list
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
# printing original list
print("The original list : " + str(test_list))
# initialization K
K = 4
# using for loop
# Incremental value initialization in Dictionary
res=dict()
for i in range(0,len(test_list)):
res[test_list[i]]=K*(i+1)
# print result
print("The Dictionary after index keys : " + str(res))
OutputThe original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
The Dictionary after index keys : {'Nikhil': 4, 'Akshat': 8, 'Akash': 12, 'Manjeet': 16}
Time complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), to store the dictionary of n key-value pairs
Method 5: Using a defaultdict and a for loop
We can uses the defaultdict class from the collections module to create a dictionary with a default value of 0 for any keys that haven't been added yet. The enumerate() function is used to iterate over the list of keys and their indices. The value for each key is then calculated using the provided formula (K*(i+1)) and assigned to the defaultdict. Finally, the dict() constructor is used to convert the defaultdict to a standard dictionary, and the result is printed.
Below is the implementation:
Python3
from collections import defaultdict
# Define the list of values to use as keys
test_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet']
# Define the increment value
K = 4
# Create a defaultdict with int type as the default value
res = defaultdict(int)
# Loop through the list of keys and their indices
for i, val in enumerate(test_list):
# Assign the key and its corresponding value to the defaultdict
res[val] = K*(i+1)
# Convert the defaultdict to a standard dictionary and print the result
print(dict(res))
Output{'Nikhil': 4, 'Akshat': 8, 'Akash': 12, 'Manjeet': 16}
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.
Similar Reads
Python | Increment value in dictionary
Sometimes, while working with dictionaries, we can have a use-case in which we require to increment a particular key's value in dictionary. It may seem quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let's discuss cer
6 min read
Python - Incremental Range Initialization in Matrix
Sometimes, while working with Python, we can have a problem in which we need to perform the initialization of Matrix. Simpler initialization is easier. But sometimes, we need to perform range incremental initialization. Let's discuss certain ways in which this task can be performed. Method #1: Using
4 min read
Python | Initializing dictionary with list index-values
While working with Python we might need to perform tasks in which we need to assign a dictionary with list values as dictionary values and index as dictionary keys. This type of problem is quite common in cases we need to perform data-type conversion. Let's discuss certain ways in which this task ca
4 min read
Python | Initializing dictionary with list index values
While working with dictionaries, we might come across a problem in which we require to attach each value in list with it's index, to be used afterwards to solve question. This technique is usually very useful in competitive programming domain. Let's discuss certain ways in which this task can be per
5 min read
Python | Initialize dictionary with None values
Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
4 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}Using defaul
2 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Letâs discuss certain way in whi
7 min read
Python - Custom dictionary initialization in list
While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom dictionaries. This task has itâs utility in web development to store records. Letâs discuss certain ways in which this task can be performed. Method #1 : Using {dict} + "*" operato
3 min read
How to Initialize Dictionary in Python
In Python dictionary, each key is unique and we can store different data types as values. The simplest and most efficient method to initialize a dictionary is using curly braces {}. This is the easiest and most common way to create a dictionary. We can use curly braces '{} ' and separate the keys an
2 min read
Python - Test for Incrementing Dictionary
Given a dictionary, test if it is incrementing, i.e. its key and values are increasing by 1. Input : test_dict = {1:2, 3:4, 5:6, 7:8} Output : True Explanation : All keys and values in order differ by 1. Input : test_dict = {1:2, 3:10, 5:6, 7:8} Output : False Explanation : Irregular items. Method 1
6 min read