Is there a way to add more dict after adding it? Django
Sorry if the title is a little difficult to understand. Not too sure how to explain this in line.
What I want to do ...
actually i have this code
output = []
objs = Model.objects.filter(abc=abc) # this would return a some queryset
for obj in objs:
output.append({
TITLE: obj.title,
TYPE: obj.type,
# I want to add something here which is kind of like, if `obj.type` is 'hello' then print obj.word
})
return output
for example if my obj.type
is "hello"
I want to
output.append({
TITLE: obj.title,
TYPE: obj.type,
WORD: obj.word,
})
if mine obj.type
is "world"
I want to
output.append({
TITLE: obj.title,
TYPE: obj.type,
NADA: obj.nada,
})
I was thinking about doing something like
output = []
objs = Model.objects.filter(abc=abc) # this would return a some queryset
for obj in objs:
if obj.type == 'hello':
output.append({
TITLE: obj.title,
TYPE: obj.type,
WORD: obj.word,
})
if obj.type == 'world':
output.append({
TITLE: obj.title,
TYPE: obj.type,
NADA: obj.nada,
})
return output
the above should work, but if there is another better way I would like to know another way to do it, because the above seems too redundant.
Thanks in advance for any advice
source to share
Good thing you have, it's okay, but if you really hate repetition of code, you can always do the dictionnary outside if first.
output = []
objs = Model.objects.filter(abc=abc) # this would return a some queryset
for obj in objs:
current_dict = {
"TITLE": obj.title,
"TYPE": obj.type,
}
if obj.type == "world":
current_dict["NADA"] = obj.nada
else:
current_dict["WORD"] = obj.world
output.append(current_dict)
return output
But you can slow down a bit ... (Though time is won by not doing the second check: P)
Use timeit ( https://docs.python.org/3/library/timeit.html ) to see if "nice code" is worth it, maybe it doesn't change much for your use case.
Also, for lovers of one liner:
As of python 3.5 and as suggested in Pep 448 , you can do:
return [
{
**{
"TITLE": obj.title,
"TYPE": obj.type
},
**{"NADA": obj.nada} if obj.type == "word" else **{"WORD": obj.word}
} for obj in Model.objects.filter(abc=abc)
]
Which can also be placed on one line. If you really love brevity, that is, but some will argue that it is much worse than you. ^ - ^
source to share
output = []
objs = Model.objects.filter(abc=abc) # this would return a some queryset
for obj in objs:
start_dict = {
'TITLE': obj.title,
'TYPE': obj.type
}
if obj.type == 'hello':
start_dict['WORD'] = obj.word
elif obj.type == 'world':
start_dict['NADA'] = obj.nada
output.append(start_dict)
return output
source to share