排序值从MySQL中获取蟒蛇
问题描述:
我连接到MySQL数据库和提取两列从MySQL的蟒蛇与排序值从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计数字典里面的唯一项目。现在我有例如:
种皮:2 TESTB:82 TESTC:102测试d:3试验E:1等..约220项
我想将字典内的项目进行排序例如根据它们的值增加到递减顺序,例如testC:102,testB:82,testD:3,test A:2,test E:1.我想知道我该怎么做。谢谢你,如果你需要进一步的信息,我可以很乐意提供。
答
我会问数据库为你做,SQL查询应为:
select test_id, count(*) as count from b.atc_id_TO_cID group by test_id order by count
,它会返回一个2列的表与为test_id,试验次数与此为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)
+0
完美。非常感谢Guillaume。有用 –
这个问题与MySQL无关,所以请删除标记。 – FDavidov
为什么不直接写正确的查询,以免在Python中做任何事情? –
好的确定。我做了:) fdavidov –