How I get the value from a dictionary if the key from all keys are the same?

Question:

I want all values from a dictionary, but I have for each value the same key. It is possible to get the values in a separately empty list?

dic = QuesModel.objects.values("ans").distinct()
print(dic) 

""" 
Output :
< QuerySet [
{'ans': 'antwort1'}, 
{'ans': 'answer2'}, 
{'ans': 'besitzt als Modelle elemente verschiedene Ereignistypen.'}, {'ans': 'als Nachrichten und Datenobjekte e dargestellt.'}, 
{'ans': '2 ist eine rationale Zahl'}, 
{'ans': 'x hat den Wert 55'}, 
{'ans': ''}]>
"""

and I want to get the values from dic in a list, like:

for key, values in dic.items(): 

but it is not working. How can I fix it?

Asked By: replaalpi

||

Answers:

You can work with .values_list(…) [Django-doc] instead:

QuesModel.objects.values_list('ans', flat=True).distinct()

Note: Models normally have no …Model suffix. Therefore it might be better to rename QuesModel to Question.

Answered By: Willem Van Onsem

Yes you can do the following:

dic1 = list(QuesModel.objects.values("ans").distinct())
answers = [i['ans'] for i in dic1]
print(answers)

Note: Models in Django don’t require model to be the suffix, so it is better to name it as Ques only or Question.

Answered By: Sunderam Dubey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.