在python中排序字典的字母数字键 [英] Sorting alphanumeric keys of a dictionary in python

查看:179
本文介绍了在python中排序字典的字母数字键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python字典,其键具有以下格局:

 <某些x位数/字母> <某些y字母数字><某些z位数字> 

我想根据这个键排序字典。
例如

  01IB0610,01IB062,01IB064 

应为 01IB062,01IB064 01IB0610



完整示例是这样的:

  {'01IB0610':{'a':[],'b':[]} '01IB062':{'a':[],'b':[]},'01IB064':{'a':[],'b':[]} 

最终输出应为: {'01IB062':{'a':[],'b':[]} '01IB064':{'a':[],'b':[]},'01IB0610':{'a':[],'b':[]}

解决方案

  import re 

def key_func(s):
返回[int(x)if x.isdigit()else x for re.findall(r'\D + | \d +',s)]

sorted_keys = sorted(d,key = key_func)

示例:

 >>> d = {'01IB0610':'foo','01IB062':'bar','01IB0604':'baz'} 
>>> sort(d,key = key_func)
['01IB062','01IB0604','01IB0610']


I have a python dictionary whose keys have the following pattern

<some x number of digits/alphabets> <some y number of alphabets><some z number of digits>

I want to sort the dictionary based on this keys. For e.g

01IB0610, 01IB062, 01IB064

should be 01IB062, 01IB064 01IB0610

Complete example is something like this:

{ '01IB0610' : {'a' : [] , 'b': [] }, '01IB062' : {'a' : [] , 'b': [] } , '01IB064' : {'a' : [] , 'b': [] }

Final Output should be:{ '01IB062' : {'a' : [] , 'b': [] }, '01IB064' : {'a' : [] , 'b': [] } , '01IB0610' : {'a' : [] , 'b': [] }

解决方案

import re

def key_func(s):
    return [int(x) if x.isdigit() else x for x in re.findall(r'\D+|\d+', s)]

sorted_keys = sorted(d, key=key_func)

Example:

>>> d = {'01IB0610': 'foo', '01IB062': 'bar', '01IB0604': 'baz'}
>>> sorted(d, key=key_func)
['01IB062', '01IB0604', '01IB0610']

这篇关于在python中排序字典的字母数字键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆