简体   繁体   中英

Dictionary output is not as expected in PYTHON

Here prsnson.result contains the data which are comming from an query. I want the expected output, but its not coming. I am using 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}

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

Integers fetched from a database is commonly returned as Long when utilizing the different database interfaces.

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

All the L means is that it's in long integer (64-bit) form, so your returned value is indeed still correct. 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. If so, you need to look back at the code that defines prsnobj and check that it was created properly. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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