Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary loops python keyvaluepair

How to find Common Keys in key value Pair which are Less than the Specified Threshold

发布于 2020-03-31 23:00:31

I have a dictonary with key value pair where I want to set threshold as less than 50% for value which basically means in any of the key value pair where value pair has value less than 50% of all values we should put that key value pair in a dictonary and afterwards we have read those pair in a dictonary and check which key values are affecting the threshold.

{('a','b'):2,('b','c'):4,('c','d'):6,('d','e'):8,('e','f'):8,('f','g'):3,('g','h'):2,('h','i'):7,(i,j):10}

As you can see in above dictonary pair (a,b) and (b,c) have value 2 and 4 which is less than 50% so here we can say because b is common in both thats why value is less than 50%.So I want to print b as output.Same in case of (f,g) and (g,h) pair so here also output will be g.

So the final output which I want is-- b,g

Kindly help I am new to Python...

Questioner
Ani
Viewed
87
Chandral 2020-02-01 14:26

Here's how I approached this problem:

  1. Extract all the keys based on the threshold of 50%
  2. Merge all the extracted keys into a single tuple
  3. Extract all the duplicate letters (i.e. the letters which caused the value to be less than the threshold) in a Set()
def get_my_data(dictionary, threshold):
    if 0 <= threshold <= 100:
        threshold = (max([value for value in dictionary.values()])) * (threshold/100) # Sets threshold value from dictionary values
        merged_keys = ()
        for key, value in dictionary.items():
            if value < threshold:
                merged_keys += key
        return set(letter for letter in merged_keys if merged_keys.count(letter) > 1)
    else:
        return f"Invalid threshold value: {threshold}, please enter a value between 0 to 100."


your_dictionary = {('a', 'b'): 2, ('b', 'c'): 4, ('c', 'd'): 6, ('d', 'e'): 8, ('e', 'f'): 8, ('f', 'g'): 3,
                   ('g', 'h'): 2, ('h', 'i'): 7, ('i', 'j'): 10}
result = get_my_data(your_dictionary, 50)
print(result)

Output

{'g', 'b'}