Ruben Oldenkamp
Ruben Oldenkamp

Reputation: 223

how to get the items from the dictionary python

I have the following dictionary:

Counter({'L': 233, 'T': 208, 'I': 169, 'G': 167, 'V': 161, 'N': 155, 'R': 151, 'S': 149, 'K': 148, 'E': 146, 'A': 144, 'Q': 131, 'P': 97, 'D': 92, 'W': 92, 'Y': 85, 'C': 80, 'F': 78, 'M': 52, 'H': 44})

Now I want to do some counting with it. But it wont work yet. I want from the 3 highest and the three lowest values the % in the total. Than I want to print it like this:

print("number 1 is:", <highestvalue>, "with this %:", <%fromhighestvalue>)

I have the sum to make it in %, but because a dict is not listed, he counts with the wrong values. I have now this for the highest values:

def most(total, som):

    a = som[list(som)[0]]
    b = som[list(som)[1]]
    c = som[list(som)[2]]

    first = (a*100)/total
    seccond = (b*100)/total
    third = (c*100)/total

    firstKey = list(som.keys())[list(som.values()).index(a)]
seccondKey = list(som.keys())[list(som.values()).index(b)]
thirdKey = list(som.keys())[list(som.values()).index(c)]

return first, seccond, third, firstKey, seccondKey, thirdKey`

Can anyone help me with this?

This is the outcome now:

first: F Procentaantal: 3.020914020139427
seccond: R Procentaantal: 5.848179705654531
third: D Procentaantal: 3.563129357087529

Upvotes: 3

Views: 81

Answers (2)

Pratik Gujarathi
Pratik Gujarathi

Reputation: 965

This works.

import operator
data  = {'L': 233, 'T': 208, 'I': 169, 'G': 167, 'V': 161, 'N': 155, 'R': 151, 'S': 149, 'K': 148, 'E': 146, 'A': 144, 'Q': 131, 'P': 97, 'D': 92, 'W': 92, 'Y': 85, 'C': 80, 'F': 78, 'M': 52, 'H': 44}
sorted_data = list(sorted(data.items(), key=operator.itemgetter(1)))
total_sum = sum(data.values())

# Print 3 highest

print sorted_data[0], sorted_data[0][1]*100/float(total_sum)
print sorted_data[1], sorted_data[1][1]*100/float(total_sum)
print sorted_data[2], sorted_data[2][1]*100/float(total_sum)

# Print 3 lowest
print sorted_data[-1], sorted_data[-1][1]*100/float(total_sum)
print sorted_data[-2], sorted_data[-2][1]*100/float(total_sum)
print sorted_data[-3], sorted_data[-3][1]*100/float(total_sum)

Upvotes: 0

user6022341
user6022341

Reputation:

Something similar to this should work:

topandlow = [(k, 100 * v / sum(som.values())) for k, v in som.most_common()[:3] + som.most_common()[-3:]]
for k, v in topandlow:
    print(k, "Procentaantal: ", v)

Upvotes: 4

Related Questions