简体   繁体   中英

Sorting a dictionary list in python 3

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.

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM