Python – Append Multitype Values in Dictionary
Last Updated :
03 May, 2023
Sometimes, while working with Python dictionaries, we can have problem in which we need to update the dictionary values, according to the data type. This type of problem can have application in many domains which include data. Lets discuss a way in which this problem can be solved.
Input : test_dict = {‘gfg’ : “”, ‘is’ : {}, ‘best’ : []}
Output : {‘gfg’: ‘geeks’, ‘is’: {‘c’: 7}, ‘best’: [4, 5]}
Input : test_dict = {‘gfg’ : “123”, ‘is’ : {}, ‘best’ : [“geeks”]}
Output : {‘gfg’: ‘123geeks’, ‘is’: {‘c’: 7}, ‘best’: [‘geeks’, 4, 5]}
Method 1: Using isinstance() + update() + extend() The combination of above functions can be used to perform this task. In this, we check for the data type of value using isinstance() and perform dictionary update using update(), list update using extend().
Python3
def update_dictionary(key, val, test_dict):
if key not in test_dict:
current_dict[key] = value
elif type (val) not in [ str , list , dict ]:
raise ValueError("Invalid Data Type ")
elif isinstance (val, list ):
test_dict[key].extend(val)
elif isinstance (val, dict ):
test_dict[key].update(val)
else :
test_dict[key] = test_dict[key] + val
return test_dict
test_dict = { 'gfg' : "geekfor", 'is' : { 'a' : 5 , 'b' : 6 }, 'best' : [ 1 , 2 , 3 ]}
print ("The original dictionary is : " + str (test_dict))
up_dict = { 'c' : 7 }
up_str = 'geeks'
up_list = [ 4 , 5 ]
res = update_dictionary( 'gfg' , up_str, test_dict)
res = update_dictionary( 'is' , up_dict, res)
res = update_dictionary( 'best' , up_list, res)
print ("The update dictionary : " + str (res))
|
Output :
The original dictionary is : {‘is’: {‘b’: 6, ‘a’: 5}, ‘best’: [1, 2, 3], ‘gfg’: ‘geekfor’} The update dictionary : {‘is’: {‘b’: 6, ‘a’: 5, ‘c’: 7}, ‘best’: [1, 2, 3, 4, 5], ‘gfg’: ‘geekforgeeks’}
Time Complexity: O(n), where n is the number of elements in test_dict.
Auxiliary Space: O(n)
Method 2: Using a for loop and dictionary comprehension
- Create a function update_dictionary_2 that takes three arguments key, val, and test_dict.
- Check if the key is already present in the dictionary. If yes, update the dictionary, else add the key-value pair to the dictionary.
- If the value is a list, loop through each item in the list and add it to the dictionary using the append() method.
- If the value is a dictionary, use dictionary comprehension to merge the two dictionaries.
- If the value is a string or a number, simply add it to the dictionary.
- Return the updated dictionary.
- Call the function update_dictionary_2 with the required arguments and print the result.
Python3
def update_dictionary_2(key, val, test_dict):
if key not in test_dict:
test_dict[key] = val
elif type (val) not in [ str , list , dict ]:
raise ValueError( "Invalid Data Type" )
elif isinstance (val, list ):
for item in val:
test_dict[key].append(item)
elif isinstance (val, dict ):
test_dict[key] = { * * test_dict[key], * * val}
else :
test_dict[key] = test_dict[key] + val
return test_dict
test_dict = { 'gfg' : "geekfor" , 'is' : { 'a' : 5 , 'b' : 6 }, 'best' : [ 1 , 2 , 3 ]}
print ( "The original dictionary is : " + str (test_dict))
up_dict = { 'c' : 7 }
up_str = 'geeks'
up_list = [ 4 , 5 ]
res = update_dictionary_2( 'gfg' , up_str, test_dict)
res = update_dictionary_2( 'is' , up_dict, res)
res = update_dictionary_2( 'best' , up_list, res)
print ( "The update dictionary : " + str (res))
|
Output
The original dictionary is : {'gfg': 'geekfor', 'is': {'a': 5, 'b': 6}, 'best': [1, 2, 3]}
The update dictionary : {'gfg': 'geekforgeeks', 'is': {'a': 5, 'b': 6, 'c': 7}, 'best': [1, 2, 3, 4, 5]}
Time complexity: O(n)
Auxiliary space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...