+

Python | Converting a list of tuples to lists of dictionary values

Method # 1: Using defaultdict () + loop
This problem can be easily solved using defaultdict () and a loop. Defaultdict provides a default dictionary container for assigning an appropriate list of values ​​to keys, so we don`t need to initialize keys with an empty list, and a loop is used to extract the same values ​​from a tuple.

# Python3 code to demonstrate how it works
# Convert list of tuples to lists of dictionary values ​​
# Using defaultdict () + loop

from collections import defaultdict

 
# initialization list

test_list = [( 1 , `gfg` ), ( 1 , `is` ), ( 2 , ` best` ), ( 3 , `for` ), ( 4 , `CS` )]

 
# print the original list

print ( "The original list is:" + str (test_list))

 
# Using def aultdict () + loop
# Convert list of tuples to lists of dictionary values ​​

res = defaultdict ( list )

for i, j in test_list:

res [i] .append (j)

 
# print result

print ( "The merged dictionary is:" + str ( dict (res)))

Exit :

The origin al list is: [(1, `gfg`), (1, `is`), (2, `best`), (3, `for`), (4, `CS`)]
The merged dictionary is: {1: [`gfg`, `is`], 2: [`best`], 3: [`for`], 4: [`CS`]}

Method # 2: Using defaultdict () + groupby ()
This method does the same thing as above, just instead of using a loop to access each pair Key-value, here we use the Python groupby library to group keys by value and then convert them to a list.

# Python3 demo code
# Convert list of tuples to lists of dictionary values ​​
# Using defaultdict () + groupby ()

from collections import defaultdict

from operator import itemgetter

from itertools import groupby

 
# initializing list

test_list = [( 1 , `gfg` ), ( 1 , `is` ), ( 2 , `best` ), ( 3 , `for` ), ( 4 , `CS` )]

  
# print original list

print ( " The original list is: " + str (test_list ))

 
# Using defaultdict () + groupby ()
# Convert list of tuples to lists of dictionary values ​​

res = dict ((k, [v [ 1 ] for v in itr]) for k, itr in groupby (

  test_list, itemgetter ( 0 )))

 
# print result

print ( " The merged dictionary is: " + str ( dict (res)))

Output:

The original list is: [(1 , `gfg`), (1, `is`), (2, `best`), (3, `for`), (4, `CS`)]
The merged dictionary is: {1: [`gfg`, `is`], 2: [`best`], 3: [`for`], 4: [`CS`]}

Get Solution for free from DataCamp guru