0

this is my code.

# Lista de usuarios
UserList = []
UserDic = {}
UserListQuery = UserProfile.objects.all()
print "PRINTING QUERY " + UserListQuery
for 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 to be a dict list. I mean, if I print UserList[0]['username'], it has to return me the username in the position 0. Well, I've many users. I use append and I'm adding the user to the list. It's not working well, it overwrites the user resulting in a one position list, the last user from UserListQuery.

help?

2 Answers2

9

The issue here is, that the same UserDic object gets used in each loop, so each time UserDic['username'] gets overwritten with the new value. To prevent this you must create a new UserDic every time. The following should work:

# Lista de usuarios
UserList = []
UserListQuery = UserProfile.objects.all()
for 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)

Snorre
  • 486
  • 3
  • 6
  • thanks, I've done it before.. And I thought that can use dict has a normal variable. Solved. –  Jun 10 '15 at 17:11
2

per my comment you should try this

user_list = []
user_list_query = user_profile.objects.all()
for user in range(0,len(user_list_query)):
    user_list.append({
        'username': user_list_query[user].user.get_username(),
        'titulo' : user_list_query[user].titulo,
        'descripcion': user_list_query[user].descripcion[:60]
    })

print user_list

note i also changed the naming convention of your objects since python is preferred to use underscores between the names instead of capital letters

an even better way (more pythonic) to do it would be to remove all the excess stuff and just go with a single line loop

user_list_query = user_profile.objects.all()
print [{'username': user_list_query[user].user.get_username(), 'titulo' : user_list_query[user].titulo,'descripcion': user_list_query[user].descripcion[:60]} for user in range(0,len(user_list_query))]
Community
  • 1
  • 1
John Ruddell
  • 25,283
  • 6
  • 57
  • 86