0

Please am following a tutorial on http://www.saltycrane.com/blog/2008/06/django-blog-project-6-creating-standard/.The code creates tags and list them by their count. Below is the code am having problems with.

def create_tag_data(posts):
tag_data = []
count = {}
for post in posts:
    tags = re.split(" ", post.tags)
    for tag in tags:
        if tag not in count:
            count[tag] = 1
        else:
            count[tag] += 1
for tag, count in sorted(count.iteritems(), key=lambda(k, v): (v, k), reverse=True):
    tag_data.append({'tag': tag,
                     'count': count,})
return tag_data

I don't understand this line

  for tag, count in sorted(count.iteritems(), key=lambda(k, v): (v, k),reverse=True):

it tells me unpacking is not supported in python 3. Am using python 3. Please how do i write that particular line in python 3.

2
  • What is the full traceback you're getting from that? Commented Sep 25, 2015 at 12:19
  • you probably want to have a different variable for count in the first part of your for, since that is for your dictionary. So, maybe for tag, tag_count in ... Commented Sep 25, 2015 at 12:19

2 Answers 2

4

You need .items and you can use itemgetter which will work in python2 or 3 and is more efficient than a lambda, taking the value first with (1, 0) to use the value as the first key to sort with:

from operator import itemgetter


count = {1: 3, 2: 4, 3: 6}
for tag, count in sorted(count.items(), key=itemgetter(1,0), reverse=True):
    print(tag, count)

Output:

3 6
2 4
1 3
Sign up to request clarification or add additional context in comments.

Comments

3

Yes, you cannot use the following in Python 3.x - lambda(k, v) - the tuple parameter unpacking , which automatically unpacks a tuple/list/sequence of two items into k and v .

Also , there is no dict.iteritems() in Python 3.x , you need to use .items() , which returns a view in Python 3.x

You can instead use -

 for tag, count in sorted(count.items(), key=lambda x: (x[1], x[0]), reverse=True):

This was introduced in Python 3.0 as part of PEP 3113 - Removal of Tuple Parameter Unpacking.

And from Python 3.x onwards dict.items() returns views instead of list , and hence the dict.iteritems() (and dict.viewkeys() and dict.viewvalues()) were removed as part of PEP 3106 - Revamping dict.keys(), .values() and .items()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.