Merge Python Key Value To List

In this tutorial, we will learn how merge python key value to list. Sometimes, while working with python we might have a problem in which we need to get the values of a dictionary from several dictionaries to be encapsulated into one dictionary. You might have seen the problems in which this concept is very useful. Let see the method of solving the given problem.

Merging Python Key Value

First of all, we have created a list of dictionaries and stored it into the variable name test_list as:

test_list=[{'gfg':2,'is':4,'best':6},
           {'it':5,'is':7,'best':8}' 
           {'cs':10}]

 

Let’s print the given dictionary that we have created as:

print(test_list)

OUTPUT:

[{'gfg':2,'is':4,'best':6}, 
{'it':5,'is':7,'best':8}' 
{'cs':10}]

We create an empty dictionary because the merging values should be added into that.Let we create a empty dictionary with name epty_dict as:

epty_dict={}

This task can be performed using a nested loop and fetching each element of a dictionary and creating a new list to new key and appending the value in case of similar key occurrence. In this we used a function setdefault(), in python, the setdefault method returns the value of a key if the key is in dictionary .if not it insert a key with value to the dictionary. And finally, we print our result of the code. This can be done as:




for sub in test_list:
    for key, val in sub.items():
        epty_dict.setdefault(key,[]).append(val)
        print("the merged values is:" +str(epty_dict))

OUTPUT:

The merged values is {'is':[4,7],'it':[5],'gfg':[2],'cs':[10],'best':[6,8]}

The whole code for this problem statement is :

test_list=[{'gfg':2,'is':4,'best':6},
           {'it':5,'is':7,'best':8}'
           {'cs':10}]
print(test_list)
epty_dict={} 
for sub in test_list: 
    for key, val in sub.items(): 
        epty_dict.setdefault(key,[]).append(val) 
print("the merged values is:" +str(epty_dict))

OUTPUT:

[{'gfg':2,'is':4,'best':6}, 
{'it':5,'is':7,'best':8}' 
{'cs':10}]

The merged values is {'is':[4,7],'it':[5],'gfg':[2],'cs':[10],'best':[6,8]}

This is how we can Merge Python Key Value To List.

You can also see:

How to check if a given point lies inside a triangle or not in Python


Leave a Reply

Your email address will not be published. Required fields are marked *