Python – Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn’t occur in any other key’s value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + count()
The combination of above functionalities can be used to solve this problem. In this, we perform the task of counting occurrence using count and extraction and testing is done using loop using conditional statement.
# Python3 code to demonstrate working of # Unique Keys Values # Using loop + count() # initializing dictionary test_dict = { 'Gfg' : [ 6 , 5 ], 'is' : [ 6 , 10 , 5 ], 'best' : [ 12 , 6 , 5 ]} # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # Unique Keys Values # Using loop + count() temp = [sub for ele in test_dict.values() for sub in ele] res = [] for key, vals in test_dict.items(): for val in vals: if temp.count(val) = = 1 : res.append(key) break # printing result print ( "The unique values keys are : " + str (res)) |
The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]} The unique values keys are : ['best', 'is']
Method #2 : Using list comprehension + any() + count()
The combination of above functions can be used to perform this task. In this, we check for the unique elements using any() and count(). This is one liner way in which this task can be performed.
# Python3 code to demonstrate working of # Unique Keys Values # Using list comprehension + any() + count() # initializing dictionary test_dict = { 'Gfg' : [ 6 , 5 ], 'is' : [ 6 , 10 , 5 ], 'best' : [ 12 , 6 , 5 ]} # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # Unique Keys Values # Using list comprehension + any() + count() res = [key for key, vals in test_dict.items() if any ([ele for sub in test_dict.values() for ele in set (sub)].count(idx) = = 1 for idx in vals)] # printing result print ( "The unique values keys are : " + str (res)) |
The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]} The unique values keys are : ['best', 'is']