Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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',]
like image 527
Luis Ramon Ramirez Rodriguez Avatar asked Dec 25 '22 07:12

Luis Ramon Ramirez Rodriguez


1 Answers

order=['one','two','three','foo']
ordered_dict = OrderedDict((k, original_dict[k]) for k in order) 
like image 75
Matteo Italia Avatar answered Jan 08 '23 15:01

Matteo Italia