-3

This is basically the same question at:

How do I sort a dictionary by value?

However instead my dictionary value is a tuple with four floats. How do I key off of an element in the nested tuple?

sorted_dict = {k: dict_cleanwhite[k] for k in 
    sorted(dict_cleanwhite.items(), key=operator.itemgetter(1), reverse=True)}

Output is:

KeyError: ('43 \n', (776.52, 466.3, 785.37504, 477.34))

How do I select the nested tuple element 776?

Started writing a function to return the tuple element:

def get_item(op_obj):
    for v in op_obj:
        return v

The problem is that the type operator.itemgetter returned is not identified, guessing to read documentation.

Rumin
  • 3,787
  • 3
  • 27
  • 30
  • 2
    Can you post a sample input and expected output? – Rakesh Jun 14 '18 at 15:45
  • 1
    Looks like you have some data quality issues. Can you post an excerpt of `dict_cleanwhite` which reproduces your error? – jpp Jun 14 '18 at 15:57
  • 1
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Jun 14 '18 at 15:58

1 Answers1

0

There are couple of problems first you shouldn't convert it back to regular dict, it will lose it's sorting. Use OrderedDict to preserve order

And to sort by first item in tuple use lambda function lambda i: i[1][0]

from collections import OrderedDict

sorted_dict = OrderedDict(sorted(dict_cleanwhite.items(), key=lambda i: i[1][0], reverse=True))
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63