Sunday, August 25, 2013

Re: django template loop collections.defaultdict(lambda: collections.defaultdict(list))

Thanks Tom for replying! 

The code used to create the dict is:

my_dict = collections.defaultdict(lambda: collections.defaultdict(list))
for obj in queryset:
    my_dict[int(obj.position.split('-')[0])][int(obj.position.split('-')[2])].append(obj)

Basically I have one field in the queryset called position (the format is N-N-N-N) and I need to create the dict as in my question.
Sincerely, I don't know how I can create the dict without using defaultdict.

D

On Saturday, August 24, 2013 2:51:56 PM UTC+2, tom wrote:
On 23 Aug 2013, at 16:58, Daviddd <davide...@gmail.com> wrote:

In my template I tried:

{% for key, groups in queryset.iteritems %}      groups = {{ groups }} <br>      {% for group_key, cols in groups.iteritems %}        cols = {{ group_key }} <br>        {% for objs in cols %}            {# rest of the code #}  

But only the first loop is evaluated

groups = (1, defaultdict(<type 'list'>, {1: [<Obj: Obj 1 by daviddd>, <Obj: Obj 2 by daviddd>, <Obj: Obj3 by daviddd>], 2: [<Obj: Obj 4 by daviddd>], 3: [<Obj: Obj 5 by daviddd>, <Obj: Obj 6 by daviddd>, <Obj: Obj 7 by daviddd>]}))    groups = (2, defaultdict(<type 'list'>, {1: [<Obj: Obj 7.7 by daviddd>]}))    groups = (3, defaultdict(<type 'list'>, {1: [<Obj: Obj 7.8 by daviddd>]}))  


Maybe I'm misreading, but aren't your inner "groupses" still defaultdicts? I think they need to be coerced to normal dicts in order for Django's template system to be able to properly iterate over them.

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate