Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create OrderedDict from dict with values of list type (in the order of list's values)

It is a bit hard for me to explain it in words, so I'll show an example:

What I have (data is a dict instance):

data = {'a':[4,5,3], 'b':[1,0,2], 'c':[6,7,8]}

What I need (ordered_data is an OrderedDict instance):

ordered_data = {'b':[0,1,2], 'a':[3,4,5], 'b':[6,7,8]}

The order of keys should be changed with respect to order of items in nested lists

like image 575
svfat Avatar asked Jan 28 '26 10:01

svfat


1 Answers

tmp = {k:sorted(v) for k,v in data.items()}
ordered_data = OrderedDict((k,v) for k,v in sorted(tmp.items(), key=lambda i: i[1]))

First sort the values. If you don't need the original data, it's OK to do this in place, but I made a temporary variable.

key is a function that returns a key to be sorted on. In this case, the key is the second element of the item tuple (the list), and since lists are comparable, that's good enough.

like image 69
jpkotta Avatar answered Jan 30 '26 23:01

jpkotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!