我连接到mysql数据库并使用python with
从mysql中获取了两列 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]
并创建了一个字典CountinmyDi来计算字典中的唯一项目。现在我举个例子:
testA:2 testB:82 testC:102测试D:3测试E:1等等..约220项
我想对字典中的项进行排序,例如根据它们的值增加到递减顺序,例如testC:102,testB:82,testD:3,测试A:2,测试E:1。我想要知道我该怎么做。谢谢,如果您需要更多信息,我很乐意提供。
答案 0 :(得分:1)
我会请求数据库为您完成,SQL查询将是:
select test_id, count(*) as count from b.atc_id_TO_cID group by test_id order by count
它会返回一个包含 test_id的2列表,使用此test_id的测试次数
如果你不能这样做,我会使用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)