Python program to unique keys count for Value in Tuple List
Last Updated :
04 May, 2023
Given dual tuples, get a count of unique keys for each value present in the tuple.
Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Output : {4: 4, 2: 3, 1: 2}
Explanation : 3, 2, 8 and 10 are keys for value 4.
Input : test_list = [(3, 4), (1, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Output : {4: 3, 2: 1, 1: 2}
Explanation : 3, 8 and 10 are keys for value 4.
Method #1 : Using loop + defaultdict()
In this, we iterate for each tuple element, having key as tuple value, and increment it with each different key encountered in the dictionary value list. Next, frequency is computed using another iteration by getting length of mapped value list, converting to set to get a unique count.
Python3
# Python3 code to demonstrate working of
# Unique keys count for Value in Tuple List
# Using loop + defaultdict()
from collections import defaultdict
# initializing list
test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
# printing original list
print("The original list is : " + str(test_list))
res = defaultdict(list)
for sub in test_list:
# getting all keys to values
res[sub[1]].append(sub[0])
res = dict(res)
res_dict = dict()
for key in res:
# getting unique key counts for each value
res_dict[key] = len(list(set(res[key])))
# printing result
print("Unique keys for values : " + str(res_dict))
OutputThe original list is : [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Unique keys for values : {4: 4, 2: 3, 1: 2}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using loop + defaultdict() + Counter()
In this, in order to reduce a computation loop, the list is constructed dynamically having just unique values. Then Counter() is used to get unique value dictionary.
Python3
# Python3 code to demonstrate working of
# loop + defaultdict() + Counter()
# Using loop + defaultdict() + Counter()
from collections import defaultdict, Counter
# initializing list
test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2),
(8, 1), (9, 1), (8, 4), (10, 4)]
# printing original list
print("The original list is : " + str(test_list))
mem_dict = defaultdict(list)
res = []
for sub in test_list:
# if not in dict, add value
if sub[0] not in mem_dict[sub[1]]:
mem_dict[sub[1]].append(sub[0])
res.append(sub[1])
# getting frequency
res = dict(Counter(res))
# printing result
print("Unique keys for values : " + str(res))
OutputThe original list is : [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Unique keys for values : {4: 4, 2: 3, 1: 2}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using count() method
Python3
# Python3 code to demonstrate working of
# Unique keys count for Value in Tuple List
# initializing list
test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
# printing original list
print("The original list is : " + str(test_list))
x=[]
for i in test_list:
i=list(i)
x.append(i[1])
d=dict()
for i in x:
d[i]=x.count(i)
# printing result
print("Unique keys for values : " + str(d))
OutputThe original list is : [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Unique keys for values : {4: 4, 2: 3, 1: 2}
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) additional space of size n is created
Method 4: using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Unique keys count for Value in Tuple List
import operator as op
# initializing list
test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2),
(8, 1), (9, 1), (8, 4), (10, 4)]
# printing original list
print("The original list is : " + str(test_list))
x = []
for i in test_list:
i = list(i)
x.append(i[1])
d = dict()
for i in x:
d[i] = op.countOf(x, i)
# printing result
print("Unique keys for values : " + str(d))
OutputThe original list is : [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Unique keys for values : {4: 4, 2: 3, 1: 2}
Time Complexity: O(N)
Auxiliary Space : O(N)
Method 5: Using numpy:
Algorithms :
- Initialize an empty list x.
- Iterate through each tuple in test_list.
- Convert the tuple to a list and append the second element of the list to x.
- Initialize an empty dictionary d.
- Iterate through each element i in x.
- Add a key-value pair to d where the key is i and the value is the number of times i appears in x.
- Print the resulting dictionary d.has context menu
Python3
import numpy as np
# initializing list
test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2),
(8, 1), (9, 1), (8, 4), (10, 4)]
# printing original list
print("The original list is : " + str(test_list))
# converting list of tuples to 2D numpy array
arr = np.array(test_list)
# extracting second column from numpy array
col = arr[:, 1]
# finding unique keys for values using numpy.unique() and numpy.bincount() functions
unique, counts = np.unique(col, return_counts=True)
unique_keys_for_values = dict(zip(unique, counts))
# printing result
print("Unique keys for values : " + str(unique_keys_for_values))
Output:
The original list is : [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Unique keys for values : {1: 2, 2: 3, 4: 4}
The time complexity :O(n), where n is the length of the input list. This is because the code iterates through the list once to extract the second element of each tuple and then again to count the number of occurrences of each second element.
The space complexity :O(k), where k is the number of unique second elements in the input list. This is because the code creates a dictionary to store the count of each unique second element, which has a space complexity proportional to the number of unique second elements.
Method 6: Using dictionary comprehension + set comprehension
Python3
# importing required module
from collections import defaultdict
# initializing list
test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
# printing original list
print("The original list is : " + str(test_list))
# using dictionary comprehension + set comprehension
# for counting unique keys for each value
res_dict = {sub[1]: len({x[0] for x in test_list if x[1] == sub[1]}) for sub in test_list}
# printing result
print("Unique keys for values : " + str(res_dict))
# Time complexity: O(n^2)
# Auxiliary space: O(n) (for res_dict)
OutputThe original list is : [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)]
Unique keys for values : {4: 4, 2: 3, 1: 2}
Time complexity: O(n^2)
Auxiliary space: O(n)
Similar Reads
Python program to extract the Unique Dictionary Value List elements
Given Dictionary with value lists, extract all unique values. Input : test_dict = {"Gfg" : [6, 7, 4, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 4, 8, 5, 2] Explanation : All distincts elements extracted. Input : test_dict = {"Gfg" : [6, 7, 6], "Geeks" : [6, 8, 5, 2]} Output : [6, 7, 8, 5, 2] Explan
6 min read
Convert List of Tuples to Dictionary Value Lists - Python
The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list.For example, given the list li = [(1, 'gfg'), (1, '
4 min read
Python | Program to count duplicates in a list of tuples
Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a
6 min read
Counting number of unique values in a Python list
Counting the number of unique values in a Python list involves determining how many distinct elements are present disregarding duplicates.Using a SetUsing a set to count the number of unique values in a Python list leverages the property of sets where each element is stored only once.Pythonli = [1,
2 min read
Python - Filter unique valued tuples
Given a Tuple list, filter tuples that don't contain duplicates. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)] Output : [(3, 5, 6, 7)] Explanation : Rest all tuples have duplicate values. Input : test_list = [(3, 5, 6, 7, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)] Output : [] E
6 min read
Python - Tuple key detection from value list
Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
6 min read
Python - Unique values count of each Key
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key. Example: Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6}, {"gfg" : 7, "is" : 3, "best" : 10}] Output : {'gfg': 2, 'is': 1, 'best': 3} Explanation : gfg ha
7 min read
Python | Assign value to unique number in list
We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id's. Let's discuss certain ways in which this problem can be solved. Method #1: Using enumerate() + list
7 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name"Then, the unique values
4 min read
Assign Ids to Each Unique Value in a List - Python
The task of assigning unique IDs to each value in a list involves iterating over the elements and assigning a unique identifier to each distinct value. Since lists in Python are mutable, the goal is to efficiently assign an ID to each unique element while ensuring that repeated elements receive the
3 min read