如何在数组中添加订单数量?

时间:2015-05-24 08:11:36

标签: python

如何在数组中添加订单数量?

我从这个Python命令中获取结果数据。

cursor = connection.cursor()
cursor.execute("SELECT animal FROM myapp_animal ORDER BY idx DESC LIMIT 3")
results = cursor.fetchall()
x = cursor.description
resultsList = []   
for r in results:
    i = 0
    d = {}
    while i < len(x):
        d[x[i][0]] = r[i]
        i = i+1
    resultsList.append(d)

return HttpResponse(resultsList)

以下是结果数组的数据:

'result' : [{'animal' : 'cat' }, {'animal' : 'dog' }, {'animal' : 'horse' }]

我想这样做:

'result' : [{'order' : '0' , 'animal' : 'cat' }, {'order':'1', 'animal' : 'dog' }, {'order' : '2', 'animal' : 'horse' }]

如何在数组中添加订单数量?

3 个答案:

答案 0 :(得分:2)

其他人解释了你的错误,但为什么不使用enumerate

>>> res = [{'animal': 'cat' }, {'animal': 'dog' }, {'animal': 'horse' }]
>>> for i, j in enumerate(res):
...      j.update({'order': i})
... 
>>> res
[{'order': 0, 'animal': 'cat'}, {'order': 1, 'animal': 'dog'}, {'order': 2, 'animal': 'horse'}]

答案 1 :(得分:0)

而不是

Output with order by difference of the two counts:
   r_id     difference of counts
   5,       0
   6,       1

使用:

d = {}

或者,如果您确实希望d = { order: i } 的值为字符串,请使用:

order

答案 2 :(得分:0)

如果你需要像dict这样的结构,但是有了排序,也许你应该注意OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict