Python – Unpacking Values in Strings
Last Updated :
10 Apr, 2023
Given a dictionary, unpack its values into a string.
Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “Gfg”, 9 : “Best”}
Output : First value is Gfg Second is Best
Explanation : After substitution, we get Gfg and Best as values.
Input : test_str = “First value is {} Second is {}”, test_dict = {3 : “G”, 9 : “f”}
Output : First value is G Second is f.
Explanation : After substitution, we get G and f as values.
Method 1: Using format() + * operator + values()
The combination of above functions can be used to solve this problem. In this, we use format to map required value with braces in string. The * operator is used to unpack and assign. The values are extracted using values().
Python3
test_str = "First value is {} Second is {} Third {}"
print ( "The original string is : " + str (test_str))
test_dict = { 3 : "Gfg" , 4 : "is" , 9 : "Best" }
res = test_str. format ( * test_dict.values())
print ( "String after unpacking dictionary : " + str (res))
|
Output
The original string is : First value is {} Second is {} Third {}
String after unpacking dictionary : First value is Gfg Second is is Third Best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2 : Using f-string interpolation and dictionary comprehension.
Step-by-step approach:
- Initialize the string with curly braces for the keys that will be replaced by values from the dictionary.
- Initialize the dictionary with keys as integers and values as strings.
- Use dictionary comprehension to create a new dictionary with keys as strings and values as the corresponding values from the original dictionary.
- Use f-string interpolation to replace the keys in the string with the values from the new dictionary.
- Print the result.
Below is the implementation of the above approach:
Python3
test_str = "First value is {first} Second is {second} Third is {third}"
print ( "The original string is : " + str (test_str))
test_dict = { 3 : "Gfg" , 4 : "is" , 9 : "Best" }
new_dict = { "first" : test_dict[ 3 ], "second" : test_dict[ 4 ], "third" : test_dict[ 9 ]}
res = test_str. format ( * * new_dict)
print ( "String after unpacking dictionary : " + str (res))
|
Output
The original string is : First value is {first} Second is {second} Third is {third}
String after unpacking dictionary : First value is Gfg Second is is Third is Best
Time complexity: O(1), as the dictionary keys are hardcoded and the format string is fixed.
Auxiliary space: O(1), as the size of the dictionaries and strings used is constant
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...