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
test_list = [ 'Nikhil' , 'Akshat' , 'Akash' , 'Manjeet' ]
print ("The original list : " + str (test_list))
K = 4
res = {val : (K * (idx + 1 )) for idx, val in enumerate (test_list)}
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
test_list = [ 'Nikhil' , 'Akshat' , 'Akash' , 'Manjeet' ]
print ("The original list : " + str (test_list))
K = 4
res = dict ( zip (test_list, range (K, len (test_list) * (K + 1 ), K)))
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
test_list = [ 'Nikhil' , 'Akshat' , 'Akash' , 'Manjeet' ]
print ( "The original list : " + str (test_list))
K = 4
res = {}
for i, val in enumerate (test_list):
res[val] = K * (i + 1 )
print ( "The Dictionary after index keys : " + str (res))
|
Output
The 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
test_list = [ 'Nikhil' , 'Akshat' , 'Akash' , 'Manjeet' ]
print ( "The original list : " + str (test_list))
K = 4
res = dict ()
for i in range ( 0 , len (test_list)):
res[test_list[i]] = K * (i + 1 )
print ( "The Dictionary after index keys : " + str (res))
|
Output
The 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
test_list = [ 'Nikhil' , 'Akshat' , 'Akash' , 'Manjeet' ]
K = 4
res = defaultdict( int )
for i, val in enumerate (test_list):
res[val] = K * (i + 1 )
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
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 defau
2 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
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 - Dictionary List Values Frequency
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the task of computing frequency of all the values in dictionary values lists. This is quite common problem and can have use cases in many domains. Let's discuss certain ways in which this task can be
6 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
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