简体   繁体   中英

create an ordered dict

I have a dict like:

original_dict = {'two':'2','three':'3','one':'1','foo':'squirrel'}

And I wanted two be in this order:

ordered_dict = OrderedDict({'one':'1','two':'2','three':'3','foo':'squirrel' })

but I don't get the same order, {'one':'1','two':'2','three':'3','foo':'squirrel'} creates a dict by itself so it doesn't work as I spected

I saw in the documentation that the sorted method can be used

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

But I don't know a function to return the order I want I tried

ordered_dict = OrderedDict(sorted(original_dict.items(),['one','two','three','foo']))

But that didn't work.

Note that the order I want can be quite arbitrary, like:

['three','foo','one','two',]
order=['one','two','three','foo']
ordered_dict = OrderedDict((k, original_dict[k]) for k in order) 

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