博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python dict sort
阅读量:4030 次
发布时间:2019-05-24

本文共 8119 字,大约阅读时间需要 27 分钟。

Note: If you want to sort a list, tuple or object in Python, checkout this article: 

The dict (dictionary) class object in Python is a very versatile and useful container type, able to store a collection of values and retrieve them via keys. The values can be objects of any type (dictionaries can even be nested with other dictionaries) and the keys can be any object so long as it's hashable, meaning basically that it is immutable (so strings are not the only valid keys, but mutable objects like lists can never be used as keys). Unlike Python lists or tuples, the key and value pairs in dict objects are not in any particular order, which means we can have a dict like this:

Although the key-value pairs are in a certain order in the instantiation statement, by calling the list method on it (which will create a list from its keys) we can easily see they aren't stored in that order:

Sorting Python dictionaries by Keys

If we want to order or sort the dictionary objects by their keys, the simplest way to do so is by Python's built-in sorted method, which will take any iterable and return a list of the values which has been sorted (in ascending order by default). There is no class method for sorting dictionaries as there is for lists, however the sorted method works the same exact way. Here's what it does with our dictionary:

We can see this method has given us a list of the keys in ascending order, and in almost alphabetical order, depending on what we define as "alphabetical." Also notice that we sorted its list of keys by its keys — if we want to sort its list of values by its keys, or its list of keys by its values, we'd have to change the way we use the sorted method. We'll look at these different aspects of sorted in a bit.

Sorting Python dictionaries by Values

In the same way as we did with the keys, we can use sorted to sort the Python dictionary by its values:

This is the list of values in the default order, in ascending order. These are very simple examples so let's now examine some slightly more complex situations where we are sorting our dict object.

Custom sorting algorithms with Python dictionaries

If we simply give the sorted method the dictionary's keys/values as an argument it will perform a simple sort, but by utilizing its other arguments (i.e. key and reverse) we can get it to perform more complex sorts.

The key argument (not to be confused with the dictionary's keys) for sorted allows us to define specific functions to use when sorting the items, as an iterator (in our dict object). In both examples above the keys and values were both the items to sort and the items used for comparison, but if we want to sort our dict keys using our dict values, then we would tell sorted to do that via its key argument. Such as follows:

With this statement we told sorted to sort the numbers dict (its keys), and to sort them by using numbers' class method for retrieving values — essentially we told it "for every key in numbers, use the corresponding value in numbers for comparison to sort it.".

We can also sort the values in numbers by its keys, but using the key argument would be more complicated (there is no dictionary method to return a key by using a certain value, as with the list.index method). Instead we can use a  to keep it simple:

Now the other argument to consider is the reverse argument. If this is True, the order will be reversed (descending), otherwise if it's False it will be in the default (ascending) order, it's as simple as that. For example, as with the two previous sorts:

These sorts are still fairly simple, but let's look at some special algorithms we might use with strings or numbers to sort our dictionary.

Sorting Python dictionaries with String and Number Algorithms

Sorting strings in alphabetical order is very common, however using sorted might not sort the keys/values of our dictin the "proper" alphabetical order, i.e. ignoring the case. To ignore the case we can again utilize the key argument and the str.lower (or str.upper) method so that all strings are the same case when comparing them:

For associating strings with numbers, we need an extra element of context to associate them properly. Let's make a new dict object first:

This contains only string keys and values, so there'd be no way to put the months in the correct order without additional context. To do so we can simply create another dictionary to map the strings to their numerical values and use that dictionary's __getitem__ method to compare the values in our month dictionary:

As we can see, it still returned a sorted list of its first argument (month). To return the months in order, we'll use a  again:

If we wanted to sort our key/value strings by the number of repeated letters in each string, we could define our own custom method to use in the sorted key argument:

Using the function can be performed as follows:

More advanced sorting functionality

Now let's say we have a dictionary keeping track of the number of students in a class for each of these months, like so:

If we want to organize the class sizes with the even numbers first and odd numbers second, we could do so with a definition like this:

Using the evens1st sorting function, gives us the following output:

Likewise we could list the odd class sizes first, and perform many other algorithms to get our sort exactly how we want. There are many other intricate sorting methods and tricks you could use with dictionaries (or any iterable object), but for now hopefully these examples have provided a good starting point.

转载地址:http://pohbi.baihongyu.com/

你可能感兴趣的文章
搞定Java面试中的数据结构问题
查看>>
深入理解Apache Flink核心技术
查看>>
SpringCloud 各组件原理图,面试必备
查看>>
面试题总结:可能是全网最好的MySQL重要知识点
查看>>
MySQL面试之数据库索引
查看>>
完整的项目管理流程,看清PMP42个过程的执行顺序
查看>>
设计模式,面试速记手册1
查看>>
设计模式,面试速记手册2
查看>>
备受面试官青睐的 Java NIO,到底和传统 IO 有啥不一样
查看>>
各大公司Java面试题超详细总结
查看>>
搞定MySQL之面经(一)
查看>>
排序算法,看这一篇就够了,含动图+Java实现
查看>>
性能指标:QPS、TPS、系统吞吐量理解
查看>>
搞清 适配器模式、代理模式和装饰者模式的不同
查看>>
一次完整的HTTP请求过程
查看>>
HTTP 与 HTTPS 的区别
查看>>
SVN E200030: There are unfinished transactions detected
查看>>
搞定Nginx高并发原理:多进程单线程和多路IO复用模型
查看>>
深入NGINX:nginx高性能的实现原理
查看>>
搞定分布式锁,主流的三种解决方案
查看>>