Python – Group list of tuples to dictionary
Last Updated :
05 Jan, 2022
Given a list of tuples, the task is to write a Python Program to get the dict into this tuple.
Example:
Input: [(1, 2, 3, 4, 5, 6), (1, 4),
(3, 5, 3, 4, 5, 6), (5, 7),
(5, 6), (4, 4)]
Output:{1: [2, 3, 4, 5, 6, 4], 3: (5, 3, 4, 5, 6), 5: [7, 6], 4: [4]}
Example 1:
Create a list of tuples as shown. Then the task here is to group the list of tuples into a dictionary. For this purpose, Create an empty dictionary as shown. Then iterate through the list of tuples to group them to the dictionary.
Python3
test = [( 1 , 2 ), ( 1 , 4 ), ( 3 , 5 ), ( 5 , 7 )]
new_dict = {}
for i in test:
if new_dict.get(i[ 0 ], 'No' ) = = 'No' :
new_dict[i[ 0 ]] = i[ 1 :]
else :
new_dict[i[ 0 ]] = new_dict.get(i[ 0 ]) + i[ 1 :]
print (new_dict)
|
Output
{1: (2, 4), 3: (5,), 5: (7,)}
As you can see in the output, the list of tuples is grouped into a dictionary where the values are still a tuple of elements.
Example 2:
If you want the values of the dictionary to be a list, then, Create a new list of tuples. The task gain is to group the list of tuples into a dictionary. For this purpose, let’s create an empty dictionary as shown. Here, the dictionary values have to be a list. The key-value pairs with a single element in the value will still be as a tuple, so convert them to lists.
For a detailed explanation go through the code along with the comments below.
Python3
test = [( 1 , 2 , 3 , 4 , 5 , 6 ), ( 1 , 4 ),
( 3 , 5 , 3 , 4 , 5 , 6 ), ( 5 , 7 ),
( 5 , 6 ), ( 4 , 4 )]
new_dict = {}
for i in test:
if new_dict.get(i[ 0 ], 'No' ) = = 'No' :
new_dict[i[ 0 ]] = i[ 1 :]
else :
new_dict[i[ 0 ]] = list (new_dict.get(i[ 0 ]) + i[ 1 :])
for k, v in new_dict.items():
if len (v) = = 1 :
new_dict[k] = list (v)
print (new_dict)
|
Output
{1: [2, 3, 4, 5, 6, 4], 3: (5, 3, 4, 5, 6), 5: [7, 6], 4: [4]}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...