I am trying to create a dict with key as name
and value as corresponding User
object.
I am using Python shell from Django shell wrapper python manage.py shell
:
>>> from django.contrib.auth.models import User
>>> names = ['carl', 'jim', 'jack', 'john', 'mark']
# Now using some dict comprehension
>>> u = {name: User.objects.get(username=name) for name in names}
NameError: global name 'User' is not defined
However, this works for me:
u = {}
for name in names:
u[name] = User.objects.get(username=name)
And I get the desired output, which is:
{
'carl': <User: carl>,
'jack': <User: jack>,
'jim' : <User: jim>,
'john': <User: john>,
'mark': <User: mark>
}
I know, there are other ways to accomplish this, but I am curious why are the dict comprehensions not working here.
Any tips?
Am I missing something here?