Home > Blockchain >  How to check how many times items from a list appear in the values of a dictionary?
How to check how many times items from a list appear in the values of a dictionary?

Time:10-01

I have a list, unique_ratios, that I have need to iterate through in a for loop and then determine how many times each item from the list appears in the values of a dictionary called comparison_dict. Here is what I have so far, but the count is wrong and does not match what the output is supposed to be.

frequencies = {}

#start count from 0 
count = 0 

#sort unique_ratios to be ascending
unique_ratios.sort()

#for each ratio in unique ratios
for i in unique_ratios: 
    #if the ratio is found in the values of the dictionary, add 1 to 
    #the count 
    if i in comparison_dict.values():
        count  = 1 
    #add the ratio as the key and the count as the value to the 
    #dictionary 
    frequencies[i] = count 

What am I doing wrong?

Just to clarify, I am forced to take this approach by looping through the list and comparing to the dictionary, so I would appreciate help in making this work.

Here is an example of the structure of the list and dictionary:

unique_ratios = [0.17, 0.20, 0.40, 0.65] 

comparison_dict = {"abc" : 0.17, "def" : 0.14, "ghi" : 0.17, "jkl" : 0.65} 

The dictionary contains 10,000 keys and values, so I have just included an example of what the list and dictionary might look like. I need to loop through each item in the list and then count how many times that item appears as a value in the dictionary.

CodePudding user response:

You need to solve two problems: count 1 for every value in the dictionary that matches i, and then do not reuse same counter.

You can calculate the count of matching values per ratio like this:

frequencies = {}

unique_ratios = [0.17, 0.20, 0.40, 0.65] 
comparison_dict = {abc : 0.17, def : 0.14, ghi : 0.17, jkl : 0.65}

for i in unique_ratios:
    frequencies[i] = sum(1 for v in comparison_dict.values() if i == v)

Result:

{0.17: 2, 0.2: 0, 0.4: 0, 0.65: 1}

CodePudding user response:

as you are requesting solution using for loop, so please find the working code here

frequencies = {}

unique_ratios = [0.17, 0.20, 0.40, 0.65]
comparison_dict = {"abc" : 0.17, "def" : 0.14, "ghi" : 0.17, "jkl" : 0.65} 

for i in unique_ratios:    
    x=0 
    # x is use to check if unique_ratio is found in the comparison_dict
    for j in comparison_dict.values():    
        if i == j:
            frequencies.setdefault(i,0)
            frequencies[i]  = 1
            x=1
            #if needed do you additional processing here 
            
    # if unique_ratio not found in the comparison_dict then set the unique_ratio value to 0
    if x==0:
        frequencies[i] = 0
            

frequencies
  • Related