0

I am using an Ordered Dictionary which contains all the values (n_estimators and error rates from an OOB estimation, as shown here.

I want to get the values with the lowest error rates first in the dictionary.

For example, below you can see that 222 has the highest error rate.

OrderedDict([('RandomForest_AWA_Fp1, max_features=7', 
    [(220, 0.10833333333333328), 
     (221, 0.10833333333333328), 
     (222, 0.10952380952380958), 
     (223, 0.10833333333333328)])
])

I want to sort this dictionary in this order: 220, 221, 223, 222 (by value in descending order)

I have tried:

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

But I do not see any difference.

ERROR I GET:

 File "<ipython-input-85-0592e683c6a9>", line 3
    pp(dict(OrderedDict(sorted([(k, sorted(v, key=min)) for k, v in d.items()], key=lambda(k, v): min(v)))))
                                                                                      ^
SyntaxError: invalid syntax
Community
  • 1
  • 1
Aizzaac
  • 3,146
  • 8
  • 29
  • 61
  • Can you clarify what the input and expected output looks like by giving a clear and simple example (e.g. 3 items)? – Robert Valencia Mar 15 '17 at 20:37
  • Are you trying to sort by the value? if so check this: [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – MattR Mar 15 '17 at 20:37

1 Answers1

0

Your dictionary is formed of one item, so I am not sure whether you wanted to sort that too. However, that appears to be the case form your linked question.

Since you mentioned 222 has the highest error value, I take it you wanted to also sort the values in the list.

>>> from pprint import pprint as pp
>>> d = OrderedDict([('RandomForest_AWA_Fp1, max_features=7', [(220, 0.10833333333333328), (221, 0.10833333333333328), (222, 0.10952380952380958), (223, 0.10833333333333328)])])
>>> pp(OrderedDict(sorted([(k, sorted(v, key=min)) for k, v in d.items()], key=lambda(k, v): min(v))))
OrderedDict([('RandomForest_AWA_Fp1, max_features=7', [(220, 0.10833333333333328), (221, 0.10833333333333328), (223, 0.10833333333333328), (222, 0.10952380952380958)])]{'RandomForest_AWA_Fp1, max_features=7': [(220, 0.10833333333333328),
                                                  (221, 0.10833333333333328),
                                                  (223, 0.10833333333333328),
                                                  (222, 0.10952380952380958)]}
Meitham
  • 9,178
  • 5
  • 34
  • 45
  • I get an error File "", line 3 pp(dict(OrderedDict(sorted([(k, sorted(v, key=min)) for k, v in d.items()], key=lambda(k, v): min(v))))) ^ SyntaxError: invalid syntax – Aizzaac Mar 15 '17 at 21:19
  • @Aizzaac that works fine here! Could you check if you missed a braces between copy/paste? – Meitham Mar 15 '17 at 21:25