简体   繁体   English

词典输出与PYTHON中的预期不符

[英]Dictionary output is not as expected in PYTHON

Here prsnson.result contains the data which are comming from an query. 此处prsnson.result包含来自查询的数据。 I want the expected output, but its not coming. 我想要预期的输出,但不会输出。 I am using python 2.5 我正在使用python 2.5

for row in prsnobj.result:
    ansdb = {row[0] : row[1]}
    print ansdb

Actual: {1L: 3L} {2L: 4L} {3L: 2L} {4L: 2L} {5L: 2L} 实际:{1L:3L} {2L:4L} {3L:2L} {4L:2L} {5L:2L}

Expected: {1: 3, 2: 4, 3: 2, 4: 2, 5: 2} 预期:{1:3,2:4,4,3:2,4:2,5:2}

Integers fetched from a database is commonly returned as Long when utilizing the different database interfaces. 当使用不同的数据库接口时,从数据库获取的整数通常返回为Long

If you want the output you're after 如果您想要输出,则需要

ansdb = {}
for row in prsnobj.result:
    ansdb[int(row[0])] = int(row[1])

Perhaps the MySQL documentation for Python could help clear things up 也许Python的MySQL文档可以帮助您解决问题

All the L means is that it's in long integer (64-bit) form, so your returned value is indeed still correct. L的全部意思是它是长整数(64位)形式,因此您返回的值确实仍然正确。 When you create a new dictionary with entries already in there (as you are), it's going to automatically convert all of the entries to long form; 当您创建一个新字典并在其中已有条目时(如您所愿),它将自动将所有条目转换为长格式。 instead you should use a tuple or simply print each one in the loop itself: 相反,您应该使用一个元组或在循环本身中简单地打印每个元组:

for row in prsnobj.result:
    print row[0] + " : " + row[1]

or 要么

for row in prsnobj.result:
    ansdb = (row[0], row[1])
    print ansdb

Depending on how your prsnobj object was defined, you may end up getting long integers still. 根据prsnobj对象的定义方式,您可能最终仍然会得到长整数。 If so, you need to look back at the code that defines prsnobj and check that it was created properly. 如果是这样,则需要回顾定义prsnobj的代码,并检查它是否正确创建。 Use printouts to make sure that the object is always in the state that you want it to be in! 使用打印输出来确保对象始终处于您希望其处于的状态!

for row in prsnobj.result:
    ansdb = {int(row[0]) : int(row[1])}
print ansdb

you result type is long, you should tranfer to int 如果结果类型很长,则应该转移到int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM