python : Sorting a Dictionary

Parquet文件格式核心原理与工程实践指南 Parquet是一种面向分析优化的列式存储文件格式,其本质是通过列式布局、自描述元数据、页级编码压缩和谓词下推四大机制,重构数据读取的物理路径与计算逻辑。它将传统‘全量加载+应用层过滤’模式,转变为‘按需加载+存储层过滤’,显著降低IO开销、内存占用与CPU解析成本。在现代数据湖架构中,Parquet已成为Spark、Trino、DuckDB等引擎跨平台互操作的事实标准,支撑高效ETL、交互式查询与实时分析。理解Parquet不仅关乎文件存储选择,更直接影响分区设计、Schema治理、查询性能调优与数据质量 阅读详情

 

2.2 Sorting a Dictionary

Credit: Alex Martelli, Raymond Hettinger

2.2.1 Problem

You want to sort a dictionary. Because sorting is a concept that only makes sense for sequences, this presumably means that you want a sequence of the values of the dictionary in the order obtained by sorting the keys.

2.2.2 Solution

The simplest approach is to sort the items (i.e., key/value pairs), then pick just the values:

def sortedDictValues1(adict):
    items = adict.items(  )
    items.sort(  )
    return [value for key, value in items]

However, an alternative implementation that sorts just the keys, then uses them to index into the dictionary to build the result, happens to run more than twice as fast (for a dictionary of a few thousand entries) on my system:

def sortedDictValues2(adict):
    keys = adict.keys(  )
    keys.sort(  )
    return [adict[key] for key in keys]

A further small speed-up (15% on my system) is to perform the last step by mapping a bound method. map is often marginally faster than a list comprehension when no lambda is involved:

def sortedDictValues3(adict):
    keys = adict.keys(  )
    keys.sort(  )
    return map(adict.get, keys)

A really tiny extra speed-up (about 3% on my system) is available in Python 2.2 by using adict._ _getitem_ _ rather than adict.get in this latest, bound-method version.

2.2.3 Discussion

The concept of sorting applies only to a collection that has order梚n other words, a sequence. A mapping, such as a dictionary, has no order, so it cannot be sorted. And yet, "How do I sort a dictionary?" is a frequent question on the Python lists. More often than not, the question is about sorting some sequence of keys and/or values from the dictionary.

A dictionary's keys can be extracted as a list, which can then be sorted. The functions in this recipe return the values in order of sorted keys, which corresponds to the most frequent actual need when it comes to sorting a dictionary. Another frequent need is sorting by the values in the dictionary, for which you should see Recipe 17.7.

The implementation choices are interesting. Because we are sorting key/value pairs by the key field and returning only the list of value fields, it seems conceptually simplest to use the first solution, which gets a list of the key/value pairs, sorts them, and then uses a list comprehension to pick the values. However, this is not the fastest solution. Instead, with Python 2.2, on dictionaries of a few thousand items, extracting just the keys, sorting them, and then accessing the dictionary for each key in the resulting list comprehension梩he second solution梐ppears to be over twice as fast.

This faster approach can be further optimized by extracting the bound method adict.get, which turns each key into its corresponding value, and then using the built-in function map to build the list by applying this callable to each item in the sorted list of keys. In Python 2.2, using adict._ _getitem_ _ rather than adict.get is even a little bit better (probably not enough to justify making your program version-dependent, but if you're already dependent on Python 2.2 for other reasons, you may as well use this approach).

Simplicity is one the greatest virtues for any program, but the second and third solutions aren't really more complicated than the first; they are just, perhaps, a little bit more subtle. Those solutions are probably worth using to sort any dictionary, even though their performance advantages are really measurable only for very large ones.

2.2.4 See Also

Recipe 17.7 for another application of sorting on dictionaries.

 

Python—Pandas学习之【排序sort Series 对于Series,排序的话有两种,沿着索引index或者沿着数值values,因此排序的时候要指明是按照哪种方式进行排序。 如果想要降序排列的话,使用ascending参数 DataFrame 1. 索引排序 对于DataFrame,沿着索引排序有两种,一种是沿着0轴,一种是沿着 1轴。 默认是axis = 0,即固定其他轴,沿着0轴。 如果想固定0轴,沿着1轴,可以设置axis = 1(或者axis = ’column‘) 2. 数值排序 对于DataFrame,数值排序的话,那到底是 阅读详情

相关推荐

AC7811无感FOC实战:从开环到闭环的电机控制调试全记录

本文详细记录了基于国产AC7811芯片实现无感FOC电机控制的全过程。从硬件软件环境搭建、开环I/F启动调试,到滑模观测器参数整定,再到平滑切入闭环及双环PID调节,提供了完整的实战步骤与参数调试心法。文章重点分享了无感控制从开环到闭环切换的关键技巧与常见问题排查清单,为工程师提供了一份避坑指南。

kotlin6android的博客 682

"To sort a dictionary" (Python recipe)

## {{{ http://code.activestate.com/recipes/52306/ (r2) # (IMHO) the simplest approach: def sortedDictValues1(adict):     items = adict.items()     items.sort()     return [value for key, value in...

wanguan2000的博客 166

InVEST模型实战指南:从水源涵养到热岛缓解的生态系统服务评估

本文提供了InVEST模型的实战指南,详细介绍了从环境搭建、数据预处理到核心模型应用的完整流程。通过水源涵养、碳存储、土壤保持和城市热岛缓解等核心模型的拆解,帮助生态学者与规划者系统量化评估生态系统服务,将复杂的生态价值转化为直观的空间数据与地图,为科学决策提供有力支撑。

weixin_29197051的博客 404

python学习笔记:算法之排序(sorting

三种基本排序策略: 选择排序(selection sort):按照由小到大或由大到小的排序要求,依次从输入列表中选出最小/大值。 冒泡排序(bubble sort):

904

Python: Sort a dictionary by value

http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value import operator x = {1: 2, 3: 4, 4:3, 2:1, 0:0} sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))

Erva的专栏 1285

Python数据结构应用5——排序(Sorting

在具体算法之前,首先来看一下排序算法衡量的标准: 比较:比较两个数的大小的次数所花费的时间。 交换:当发现某个数不在适当的位置时,将其交换到合适位置花费的时间。 冒泡排序(Bubble Sort) 这是一个面试经常考的排序,虽然简单,但是要保证一点都不出错也不简单。 冒泡,顾名思义,每一次冒出一个泡泡出来,这个泡泡是剩余数中最大的那个数。所以,如果有n个数待排序,那么需要冒(n-1)次泡泡。...

weixin_30426957的博客 303

python函数的位置参数(Positional)和关键字参数(keyword)

python函数具有各种灵活的参数, 功能着实强大. 不过因为过于灵活, 故比较难于理清, 所以给初学者带来了不小的困扰. 以下是我搜集的资料, 力图将这个问题明朗化. _ 1. parameter 和 argument 以前一直认为这两个单词的含义是相同的, 今天才发现其实不然. parameter为函数定义时的叫法, 它指明了函数可以接受的argument类型. 可以理解为C语言中的形参; argument为函数调用时的叫法, 可以理解为实参, 即传入的值; 下面的文档是我从pytho...

souching的专栏 8959

python字典排序_python Sorting Lists Tuples Dictionary排序操作

今天学习pythonLists Tuples Dictionary排序操作,并记录学习过程欢迎大家一起交流分享。新建一个python文件命名为py3_sorting.py,在这个文件中进行操作代码编写:#定义一个listnums = [9,2,8,1,4,5,7,6,3]#使用sorted()函数排序#定义一个变量sort_nums接收sort_nums = sorted(nums)print(...

weixin_39791386的博客 80

720. Longest Word in Dictionary python

class Solution(object): def longestWord(self, words): """ :type words: List[str] :rtype: str """ wset = set(['']) ans = '' for word in sorte...

mario_mmh的博客 302

Python sorting list of dictionaries by multiple keys

如何list里对dict类型的数据按 多字段排序,不限制数据类型 数字、str、date类型都可以 def multikeysort(items, columns): from operator import itemgetter comparers = [ ((itemgetter(col[1:].strip()), -1) if col.startswith('-') e

liukeforever的专栏 983

Python前缀树最佳实践:使用PyGTrie优化自动补全与搜索功能

PyGTrie是一个功能强大的Python前缀树(Trie)数据结构库,专门为高效处理前缀匹配和搜索优化而设计。如果你正在寻找一个简单易用且性能优越的解决方案来实现自动补全、搜索建议或路由匹配功能,那么PyGTrie绝对是你的最佳选择。🎯 这个库不仅提供了完整的字典接口,还支持多种前缀操作,让你的代码更加简洁高效。 ## 🔍 什么是前缀树? 前缀树(Trie)是一种特殊的树形数据结构,用于

gitblog_00871的博客 370

Python+Unity构建Galgame电影模式播放引擎:架构设计与工程实践

进程间通信(IPC)是连接不同软件模块、实现协同工作的关键技术,其核心原理在于通过特定机制在不同进程间交换数据与指令。在游戏开发与多媒体应用领域,高效的IPC方案能显著提升系统模块化程度与性能表现。Python以其强大的文本处理与逻辑控制能力,常被用于游戏脚本解析与业务逻辑调度;而Unity则凭借其工业级的图形渲染与跨平台能力,成为高性能表现层的首选。将两者结合,通过TCP Socket等通信桥梁构建松耦合架构,能够充分发挥各自优势,实现复杂应用的快速开发与高效运行。这一技术组合在自动化游戏剧情播放、交互式

weixin_30565327的博客 434

leetcode:字母异位词分组

方法一: class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dic = {} for i in strs : key = str(sorted(i)) #sorted返回新的列表 if key in dic : dic[key].append(i)

Justinboy的博客 176

PyGTrie高级特性:PrefixSet与多模式字符串匹配应用指南

PyGTrie是一个强大的Python库,专门实现了前缀树(Trie)数据结构,提供高效的字符串前缀匹配和存储功能。在前100个字的介绍中,让我们明确PyGTrie的核心价值:这是一个专门处理字符串前缀匹配的Python库,通过前缀树数据结构实现了高效的键值存储和检索,特别适合处理字典查找、自动补全和多模式匹配等场景。本文将深入探讨PyGTrie的高级特性,特别是PrefixSet类的应用,以及如

gitblog_00848的博客 842

如何用PyGlossary构建跨平台词典格式转换生态系统

在开源词典应用生态中,格式碎片化一直是开发者面临的核心痛点。不同设备、不同操作系统、不同词典软件使用各自专有的词典格式,导致用户无法自由选择工具,开发者难以构建统一的数据管道。PyGlossary正是为解决这一难题而生的技术桥梁——一个基于Python的词典格式转换引擎,通过插件化架构连接了超过50种词典格式,为开源词典生态系统提供了统一的数据交换层。 ## 核心理念:格式无关的词典数据抽象

gitblog_00810的博客 636

sortings in python

这篇主要写几种sort的方法,后面还会持续更新。 1. heapsort heap sort uses an array as a full tree to sort.  time complexity is nlogn  space is O(1) because  it sorts in place. it requires random access so we use array

hyperbolechi的专栏 676

深入理解python中的排序sort

基本排序 Sorting Basics key函数Key Functions operator库函数自定义排序( Operator Module Functions) 升序和降序Ascending and Descending 排序的稳定性和复杂排序 (Sort Stability and Complex Sorts) 传统的DSU(Decorate-Sort-Undecorate)的排序方法...

weixin_33754065的博客 329

pyspark.sql.Row 使用 dictionary 初始化的方法 “TypeError: sequence item 0: expected string, dict found”

from pyspark.sql import Row row_dict = {'C0': -1.1990072635132698, 'C3': 0.12605772684660232, 'C4': 0.5760856026559944, 'C5': 0.1951877800894315, 'C6':...

CY_TEC的博客 3241

python经典算法代码_python实现的几个经典的排序算法

# some complex sorting algorithmdef shell_sort(sort_list):''' (list) -> NoneSort the sort_list.'''increment = len(sort_list)iter_len = len(sort_list)while increment > 1:increment = increment // ...

weixin_39747721的博客 116

Python调用impala出现:TypeError: expecting list of size 2 for struct args

多进程访问调用impala,出现TypeError: expecting list of size 2 for struct args raise self._value TypeError: expecting list of size 2 for struct args 极大可能是因为thrift 版本问题, https://github.com/getredash/...

谷雨的博客 1073

TPS552882-Q1-车规级.pdf

TPS552882-Q1-车规级.pdf

上一篇: 在django中导出excel文件
下一篇: 解决django 0.96版本与PostgreSQL 8.3.1不兼容的问题
gyfang
博客等级 码龄18年 13粉丝 5原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值