Python – Dictionary Tuple values update
Sometimes, while working with Tuple data, we can have problem when we perform its editions, reason being it’s immutability. This discusses the editions in tuple values in dictionary. This can have application in many domains as dictionary is often popular data type in web development and Data Science domains. Let’s discuss certain ways in which this problem can be solved.
Input :
test_dict = {‘Gfg’ : (5, 6, 7, 8)}
K = 2
Output : {‘Gfg’: (10, 12, 14, 16)}
Input :
test_dict = {‘Gfg’ : (5, ), ‘is’ : (6, ), ‘best’ : (7, )}
K = 7
Output : {‘Gfg’: (35, ), ‘is’: (42, ), ‘best’: (49, )}
Method #1 : Using generator expression + dictionary comprehension
The combination of above functionalities offer one liner brute force way to solve this problem. In this, we perform the task of edition using generator expression and dictionary comprehension to remake dictionary with edited values.
Python3
test_dict = { 'Gfg' : ( 5 , 6 ), 'is' : ( 7 , 8 ), 'best' : ( 10 , 11 )}
print ( "The original dictionary is : " + str (test_dict))
K = 3
res = {key: tuple (idx * K for idx in val)
for key, val in test_dict.items()}
print ( "The edited tuple values : " + str (res))
|
Output :
The original dictionary is : {'Gfg': (5, 6), 'is': (7, 8), 'best': (10, 11)}
The edited tuple values : {'Gfg': (15, 18), 'is': (21, 24), 'best': (30, 33)}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using map() + lambda() + dict()
The combination of above functionalities also offer a way to solve this problem. In this, assignment of values is done using lambda() and construction of dictionary using dict(). The task of extending logic to each keys is done using map().
Python3
test_dict = { 'Gfg' : ( 5 , 6 ), 'is' : ( 7 , 8 ), 'best' : ( 10 , 11 )}
print ( "The original dictionary is : " + str (test_dict))
K = 3
res = dict ( map ( lambda sub: (sub[ 0 ], (sub[ 1 ][ 0 ] * K,
sub[ 1 ][ 1 ] * K)), test_dict.items()))
print ( "The edited tuple values : " + str (res))
|
Output :
The original dictionary is : {'Gfg': (5, 6), 'is': (7, 8), 'best': (10, 11)}
The edited tuple values : {'Gfg': (15, 18), 'is': (21, 24), 'best': (30, 33)}
The time complexity of this code is O(N), where N is the number of key-value pairs in the dictionary.
The space complexity of this code is also O(N), where N is the number of key-value pairs in the dictionary.
Last Updated :
13 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...