Issue
I'm trying to create a dictionary with some specific values but it gets the same values multiple times:
readers = Readers.objects.all()
count = 0
readersResult = {}
test = {
"avatar": "",
"firstName": "",
"percent": "",
"lastName": ""
}
for reader in readers:
test["percent"] = "value from another place"
test["firstName"] = reader.firstName
test["lastName"] = reader.lastName
test["avatar"] = reader.avatar
print("TEST: ", test)
readersResult[count] = test
count = count + 1
print("RESULT":, readersResult)
My output is:
web_1 | TEST: {'avatar': '/images/avatars/71.png', 'firstName': 'abc', 'percent': '37.08999158957107', 'lastName': 'def'}
web_1 | TEST: {'avatar': '/images/avatars/61.png', 'firstName': 'abc', 'percent': '4.037005887300253', 'lastName': 'def'}
web_1 | RESULT: {0: {'avatar': '/images/avatars/61.png', 'firstName': 'abc', 'percent': '4.037005887300253', 'lastName': 'def'}, 1: {'avatar': '/images/avatars/61.png', 'firstName': 'abc', 'percent': '4.037005887300253', 'lastName': 'def'}}
What am I doing wrong?
Solution
Here, in your code, you make a dict
named test, and then in each loop iteration you add it again to the readersResult
.
test = {
"avatar": "",
"firstName": "",
"percent": "",
"lastName": ""
}
for reader in readers:
test["percent"] = "value from another place"
test["firstName"] = reader.firstName
test["lastName"] = reader.lastName
test["avatar"] = reader.avatar
print("TEST: ", test)
readersResult[count] = test
count = count + 1
You need to create a new dict
with each loop iteration. So exchange this part of your code to this:
for reader in readers:
test = {}
test["percent"] = "value from another place"
test["firstName"] = reader.firstName
test["lastName"] = reader.lastName
test["avatar"] = reader.avatar
print("TEST: ", test)
readersResult[count] = test
count = count + 1
PS: You don't need to use the below code to define the keys in the dictionary and then set its values somewhere else. So you can change:
teste = {
"avatar": [],
"firstName": [],
"percent": [],
"lastName": []
}
with:
test = {}
Answered By - Happy Ahmad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.