Python dict inside list doesn't append -


this code.

# lista de usuarios userlist = [] userdic = {} userlistquery = userprofile.objects.all() print "printing query " + userlistquery user in range(0,len(userlistquery)):     userdic['username'] = userlistquery[user].user.get_username()     userdic['titulo'] = userlistquery[user].titulo     userdic['descripcion'] = userlistquery[user].descripcion[:60]     userlist.append(userdic)  print "printing list " + userlist print "printing list 0 " + userlist[0] 

i want userlist dict list. mean, if print userlist[0]['username'], has return me username in position 0. well, i've many users. use append , i'm adding user list. it's not working well, overwrites user resulting in 1 position list, last user userlistquery.

help?

the issue here is, same userdic object gets used in each loop, each time userdic['username'] gets overwritten new value. prevent must create new userdic every time. following should work:

# lista de usuarios userlist = [] userlistquery = userprofile.objects.all() user in range(0,len(userlistquery)):     userdic = {}     userdic['username'] = userlistquery[user].user.get_username()     userdic['titulo'] = userlistquery[user].titulo     userdic['descripcion'] = userlistquery[user].descripcion[:60]     userlist.append(userdic)  print userlist 

(untested code)


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -