0

I connected to mysql database and fetched two columns from mysql with python with

    query  = ('select test_id, a_id from b.atc_id_TO_cID ')


    cursor.execute(query)
    rows = cursor.fetchall()



    CountinmyDi = {}

    for row in rows:

            if not row[0] in CountinmyDi.keys():
                    CountinmyDi[row[0]] = 1
            else :
                    CountinmyDi[row[0]] += 1
    for key in CountinmyDi.keys():
                    print str(key) + ":" ,CountinmyDi[key]

and created a dictionary CountinmyDi to count the unique items inside the dictionary. Now i have for example :

testA : 2 testB : 82 testC:102 test D : 3 test E:1 and so on .. about 220 items

I want to sort the items inside my dictionary for example increasing to decreasing order based upon their values for instance testC : 102, testB : 82 , testD :3 , test A :2 , test E : 1. I would like to get an idea how i could do that . Thank you and if you need further infos, i could gladly provide.

Acerace.py
  • 679
  • 3
  • 9
  • 25

1 Answers1

1

I would ask the database to do it for you, SQL query would be:

select test_id, count(*) as count from b.atc_id_TO_cID group by test_id order by count

and it will return a 2 column table with test_id, number of tests with this test_id

If you can't do it this way, I would use a Python built-in Counter:

from collections import Counter

query  = ('select test_id, a_id from b.atc_id_TO_cID ')
cursor.execute(query)

test_counter = Counter(row[0] for row in cursor.fetchall())

for test_id, count in test_counter.most_common():
    print(test_id, ":", count)
Guillaume
  • 5,497
  • 3
  • 24
  • 42