Dictionary pagination

136 views
Skip to first unread message

David

unread,
Nov 4, 2009, 1:32:49 PM11/4/09
to Django users
Hello,

I just wonder if anybody has handled this before. Here is a 2-D
dictionary.

dict[key_1] = {'a':'aa', 'b':'bb', 'c':'cc'}
dict[key_2] = {'a':'dd', 'b':'ee', 'c':'ff'}
dict[key_3] = {'a':'eef', 'b': 'ff', 'c':'ghh'}
............

Assume that this dict is so long that I need to paginate. Do I need to
convert it to a list in order to use Paginator
?

Is there a good way to paginate this dictionary?

Thanks for your ideas.


Bill Freeman

unread,
Nov 4, 2009, 2:01:37 PM11/4/09
to django...@googlegroups.com

You at least need to list the keys, say by using the keys() method.
The trouble with
thinking of paginating a dictionary is that it has no inherent order.
When you go back
for items n through 2n-1, for example, there is no guarantee that what
you get won't
share items with the first 0-n. That the order may seem stable in
casual testing is an
implementation detail that you shouldn't depend on.

Probably you want to sort this somehow too, so that the presentation
order makes sense.
So something like:

ks = d.keys()
ks.sort()

Then for page p of n items:

for k in ks[n*(p-1):n*p]:
v = d[k]

Note that if pages are displayed across multiple requests, you need to
put ks somewhere that its value will be preserved until the next
request. Or if you're sure that d won't change between requests, just
do the call to the keys method and the sort each time.

[Note, too, re your sample, that "dict" is a bad name for a dictionary
variable, because it is also the name of the type. It will work, but
it will get confusing.]

Bill

David

unread,
Nov 4, 2009, 2:28:27 PM11/4/09
to Django users
Thanks Bill. Your reply is quite helpful.
Reply all
Reply to author
Forward
0 new messages