Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.4 Django 'QueryDict' object has no attribute 'iterkeys'

I am trying to run through the POST dictionary but for some reason when I run my code with python 3.4 instead of python 2.7 I run into a 'QueryDict' object has no attribute 'iterkeys' error. Here is the code I am running:

def printKeys(request):
    for a in sorted(request.POST.iterkeys()):
        print(a)
like image 540
Chase Roberts Avatar asked Oct 21 '14 16:10

Chase Roberts


1 Answers

I assume that QueryDict is a subclass of the built-in dict. Dictionaries do not have .iterkeys (neither .itervalues or .iteritems) on python 3.x. The methods .keys, .values, .items return directly an iterable view of the underlying dictionary rather than constructing (possibly) expensive lists.

If you want to construct a list out of those, you have to do it explicitly:

keys = list(request.POST.keys())

or more succinctly, you can just pass the dict to list, since the dictionaries are iterated per default on the keys.

keys = list(request.POST)

However, you can call sorted directly on an iterable, so this is just fine:

sorted_keys = sorted(request.POST)

Your function can be rewritten as:

def print_keys(request):
   print('\n'.join(sorted(request.POST)))

And this should work on both python 2.7 and 3.4.

like image 86
bgusach Avatar answered Nov 18 '22 18:11

bgusach