Python | Categorize tuple values into dictionary value list

Sometimes, while working with Python, we might face a problem in which we have data in form of list of tuples, and what we intend is, to categorize them into dictionary with a value list of tuples. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using setdefault() + loop
This task can easily be performed using setdefault(). In this, we just take key and value pair of tuple by iteration and setdafault() is used to assign value to corresponding key of dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
# Using setdefault() + loop
  
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
  
# printing original list
print("The original list : " +  str(test_list))
  
# Using setdefault() + loop
# Categorize tuple values into dictionary value list
res = {}
for i, j in test_list:
     res.setdefault(j, []).append(i)
  
# printing result 
print("The dictionary converted from tuple list : " + str(res))

chevron_right


Output :



The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {2: [3], 3: [1, 2, 5], 4: [1, 6]}

 

Method #2 : Using dict() + list comprehension + frozenset()
The combination of above methods can be used to perform this particular task. In this, the logical computations are done in comprehension with the help of frozenset() and the container is converted to dictionary using dict().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
# Using dict() + list comprehension + frozenset()
  
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
  
# printing original list
print("The original list : " +  str(test_list))
  
# Using dict() + list comprehension + frozenset()
# Categorize tuple values into dictionary value list
res = dict((key, [i[0] for i in test_list if i[1] == key])
             for key in frozenset(j[1] for j in test_list))
  
# printing result 
print("The dictionary converted from tuple list : " + str(res))

chevron_right


Output :

The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {2: [3], 3: [1, 2, 5], 4: [1, 6]}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.