简体   繁体   中英

How to change order in OrderDict?

I have dictionary

from collections import OrderedDict 

md = {"r3":"piz","r1":"pic","r9":"piz","r12":"pic","r19":"lia","r2":"kurcc","r21":"jes","r99":"pic","r111":"kurcc","r116":"kurcc","r211":"ar","r221":"buc"}

print (OrderedDict(sorted(md.items(), key=lambda t: t[0])))

I want to sort it,from lowest number.But I got

OrderedDict([('r1', 'pic'), ('r111', 'kurcc'), ('r116', 'kurcc'), ('r12', 'pic'), ('r19', 'lia'), ('r2', 'kurcc'), ('r21', 'jes'), ('r211', 'ar'), ('r221', 'buc'), ('r3', 'piz'), ('r9', 'piz'), ('r99', 'pic')])

How should I change my code to have r1,r2,r3 order?

If all keys are of the form 'r???' with ??? an integer, we can use the following sorting key:

OrderedDict(sorted(md.items(), key=lambda t: t[0]))

So here we first take the key with t[0] like you did yourself. Next we take the substring that starts at index 1 (so we drop the 'r' ), and finally we cast it to an int(..) to perform numerical comparisons.

This generates:

>>> OrderedDict(sorted(md.items(), key=lambda t: int(t[0][1:])))
OrderedDict([('r1', 'pic'), ('r2', 'kurcc'), ('r3', 'piz'), ('r9', 'piz'), ('r12', 'pic'), ('r19', 'lia'), ('r21', 'jes'), ('r99', 'pic'), ('r111', 'kurcc'), ('r116', 'kurcc'), ('r211', 'ar'), ('r221', 'buc')])

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